一、导包(导入需要的模块和库)
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
二、分页(找出每一页网站网址的不同之处)
for page in range(1, 11):
三、获取网址放入URL,以及伪装爬虫,获取User-Agent
URL = f'https://www.chinanews.com/scroll-news/news{page}.html'
Headers = {
'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
}
四、向网站所在服务器发送请求,拿到响应结果
response = requests.get(url=URL, headers=Hesders)
print(response.text)
五、判断状态码是否是200(状态码为200时正常)
result = response.text if response.status_code == 200 else ''
六、使用bs4模块将网页源代码转为树结构
soup = BeautifulSoup(result, html.parser)
七、最后通过标签选择器拿到所需要的目标
liList = soup.select('html > body > div.w1280.mt20 div.content_list > ul > li')
for i in liList:
if i.select('li > div.dd_lm > a') != []:
newsType = i.select_one('li > div.dd_lm > a').text
newsTitle = i.select_one('li > div.dd_bt > a').text
newsLink = 'https://www.chinanews.com' + i.select_one('li > div.dd_bt > a').attrs['href']