用bs4从网页爬取信息
- 导入必要的库:
import requests
from bs4 import BeautifulSoup
- 发送请求获取网页源代码:
url = "https://www.example.com"
response = requests.get(url)
html = response.text
- 解析网页源代码:
soup = BeautifulSoup(html, 'html.parser')
- 从网页中找到需要的信息:
# 找到所有的p标签
p_tags = soup.find_all('p')
# 找到第一个a标签
a_tag = soup.find('a')
# 找到所有class属性为"example"的div标签
div_tags = soup.find_all('div', {'class': 'example'})
- 获取标签的属性和文本内容:
# 获取a标签的href属性和文本内容
a_href = a_tag['href']
a_text = a_tag.text
# 获取第一个p标签的文本内容
p_text = p_tags[0].text
- 遍历标签的子节点:
# 遍历div标签下的所有p标签
for p_tag in div_tags[0].find_all('p'):
print(p_tag.text)
- 使用CSS选择器查找标签:
# 找到id属性为"example"的div标签
div_tag = soup.select_one('#example')
# 找到所有class属性为"example"的p标签
p_tags = soup.select('.example p')
完整代码示例:
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com"
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
# 找到第一个a标签
a_tag = soup.find('a')
# 获取a标签的href属性和文本内容
a_href = a_tag['href']
a_text = a_tag.text
# 找到所有class属性为"example"的div标签
div_tags = soup.find_all('div', {'class': 'example'})
# 遍历div标签下的所有p标签
for p_tag in div_tags[0].find_all('p'):
print(p_tag.text)
# 找到id属性为"example"的div标签
div_tag = soup.select_one('#example')
# 找到所有class属性为"example"的p标签
p_tags = soup.select('.example p')
``
原文地址: https://www.cveoy.top/t/topic/ftuf 著作权归作者所有。请勿转载和采集!