from bs4 import BeautifulSoup import requests import csv
首先确定爬取网页,然后设置请求头header,那么如何设置呢?请往下看 打开任意浏览器->F12->点开Network->F5->Header处找到request headers,这个就是浏览器的请求报头了。
from bs4 import BeautifulSoup import requests from requests.exceptions import RequestException def getHtml(url): try: response = requests.get(url, headers='Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36' ) if response.status_code == 200: return response.text except RequestException: print('===request exception===') return None此时我们已经抓取到一个response,接下来我们需要对response进行解析
#使用BeautifulSoup函数 soup = BeautifulSoup(html, 'lxml')转成如下形式: 此时我们可以使用soup.find()、soup.findAll()进行查找需要的文本 可以在网页中快速找到文本所在的模块,即F12->Elements,选中模块即在网页上标记出来,如下图所示
#先使用soup.find(),找到dealTitle下的模块 m_dealTitle=soup.find("div",id="dealTitle") #接着使用findAll筛选出所有<h1>...</h1>中...的内容 deal_title = m_dealTitle.findAll('h1')[0].contents[0].strip().strip('\n').replace(',', '')