了解网络爬虫使用Python实现基础爬虫过程
warning:
这篇文章距离上次修改已过187天,其中的内容可能已经有所变动。
import requests
from bs4 import BeautifulSoup
def simple_crawler(url, keyword):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
# 使用BeautifulSoup查找包含关键字的段落
paragraphs = soup.find_all('p', string=[lambda text: keyword in text if text else False])
for p in paragraphs:
print(p.text)
else:
print(f"Failed to retrieve the webpage: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"There was a problem: {e}")
# 使用示例
simple_crawler('https://www.example.com', '关键字')
这段代码定义了一个简单的网络爬虫函数simple_crawler
,它接受一个URL和一个关键字作为参数。函数使用requests
库获取网页内容,并使用BeautifulSoup
解析网页。然后,它查找包含关键字的段落并打印它们的文本。这个例子展示了如何使用Python进行基本的网页爬取和内容提取。
评论已关闭