第一篇爬虫文章
Hello CSDN!
我是一名python新手,前些天自己写了个爬取光明日报的爬虫练习,现在在博客中分享出来。
需要用到的库
-
requests库
如果你的电脑上没有这个库,可以通过在命令行中输入 pip install requests 安装。 -
BeautifulSoup库
“美味的汤”!
我们通过BeautifulSoup这个强大的库来解析数据和提取数据。
如果你的电脑上没有这个库,可以通过在命令行中输入 pip install beautifulsoup4 安装。 -
fake_useragent库
我们通过使用这个库来伪造useragent。
如果你的电脑上没有这个库,可以通过在命令行中输入 pip install fake_useragent 安装。
思路分析
爬取新闻网站上的新闻?听起来是个很困难的事情。
我们尝试一下将这个大问题拆分成小问题,再逐步解决小问题,然后将小问题的结果组合起来。
先把这堆库一股脑丢进去。
import requests
import time
from bs4 import BeautifulSoup
import fake_useragent
ua = fake_useragent.UserAgent()
我们要将爬取到的新闻存储下来,那么就要用到文件读写。
def write_news(a,word):#调用此函数可以完成文件写入
with open(a,mode='a',encoding='utf-8') as file:
file.write(word)
file.write('\n')
一般新闻的标题都是用h1标签存储,正文内容则用p标签存储。
我们用开发者工具检查其网页结构,结果确实如此。
OK,那我们就调用BeautifulSoup库里的方法吧。细节在此不做赘述了。
直接show my code.
def get_guangming_news(url,a): #调用此函数获取新闻正文
headers={
'User-Agent':str(ua.random)}
res=requests.get(url,headers=headers)
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')
h1=soup.find('h1')#找到标签h1
h1_content=h1.text
write_news(a,h1_content)
items=soup.find_all('div',class_='u-mainText')
for item in items:
items=item.find_all('p'