import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.57'
}
res = requests.get('http://bj.xiaozhu.com/',headers=headers)
soup = BeautifulSoup(res.text,'html.parser')
try:
print(soup.prettify())
except ConnectionError:
#出现错误执行下面操作
print('拒绝连接')BeautifulSoup支持的第三方解析器注意: BeautifulSoup 库官方推荐使用 lxml 作为解析器 因为效率史高
得到 Soup 文档可 以使用自nd()和 find_all ()方法及 selector() 方法定位需要
素了。 find () find all () 方法用法相似, BeautifulSoup 文档 这两个方法
这样的:
find_all方法
soup.find_all('div',"item")
soup.find_all('div',classname='item')
soup.find_all('div',attrs={"class":"item"})selector()方法
soup.selector(div.item>a>h1)
打开浏览器检查,在提取的数据位置选择检查,选中元素复制