Python网页抓取:用requests和BeautifulSoup提取文本内容
要抓取网页中的文字,可以使用Python的requests库和BeautifulSoup库。
- 使用requests库发送HTTP请求,获取网页内容。
import requests
url = 'https://www.example.com'
response = requests.get(url)
if response.status_code == 200:
html = response.text
# print(html)
else:
print('Failed to get the webpage.')
- 使用BeautifulSoup库解析HTML文档,提取需要的文本内容。
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
text = soup.get_text()
print(text)
在上面的代码中,我们使用BeautifulSoup库的get_text()方法来提取HTML文档中的文本内容,然后将其打印出来。
你也可以通过BeautifulSoup库的find()和find_all()方法来查找特定的HTML元素,然后提取其文本内容。
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
title = soup.find('title').get_text()
print(title)
原文地址: https://www.cveoy.top/t/topic/loLl 著作权归作者所有。请勿转载和采集!