python爬虫(1)

it2022-05-05  135

python爬虫(1)

一、需要的包二、爬取网页三、解析网页四、保存 Python爬取网页内容原理:模拟用户在发起一次请求,保存html文件,从文件中获取想要的内容。 流程如下:

爬取网页 解析网页 获取相关内容 保存

一、需要的包

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(',', '')

四、保存

import csv def save2csv(content): with open('my_content.csv', 'a+', newline='', encoding='utf-8') as csvfile: writer = csv.writer(csvfile) writer.writerow(content)

最新回复(0)