13用BeautifulSoup爬取网站

发布时间 2023-08-12 16:38:14作者: 冷夜O

 代码如下

from bs4 import BeautifulSoup
import requests
'''
本例子通过BeautifulSoup 的常用方法find_all 查询出所有包含电影名字的a标签的父节点h4,再通过父节点遍历得到a标签中的文本。
find_all 里面的参数一般是class_ 、id、name等html属性值,批量爬取数据时往往使用的是class属性。
目标html结构

<h4 class="title text-overflow">
    <a href="/vod/47562.html" title="梦游乐园">梦游乐园</a>
</h4>
BeautifulSoup 的作用不仅如此,还可以获取属性值等等,根据网页结构和属性捕获数据。
'''


req=requests.session()

headers = {
    'authority': 'fsbj001.com',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'cache-control': 'no-cache',
    'pragma': 'no-cache',
    'referer': 'https://fsbj001.com/list/dianying-1.html',
    'sec-ch-ua': '"Not/A)Brand";v="99", "Google Chrome";v="115", "Chromium";v="115"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
}

response = req.get('https://fsbj001.com/list/dianying-1.html', headers=headers)
soup = BeautifulSoup(response.text,'lxml')

h4_list = soup.find_all(class_='title text-overflow')
for h4 in h4_list:
    print(h4.a.string)

 输出结果

兴安岭猎人传说2
星条红与皇室蓝
金牌保镖
谍之心
关于我和鬼变成家人的那件事
白日青春
爷爷的人生滑板
玛丽·塞莱斯特的附魔
扫毒3:人在天涯粤语
72小时-黄金行动
扫毒3:人在天涯国语
不要见怪
河畔城市
亚当2019
...