import requests
from bs4 import BeautifulSoup
import random
url = 'https://example.com'
# 随机选择一个 User-Agent
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',
# 更多的 User-Agent
]
headers = {
'User-Agent': random.choice(user_agents)
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
# 提取需要的信息
# 例如,找到所有的标题
titles = soup.find_all('h1')
for title in titles:
print(title.text)
else:
print('Failed to retrieve the webpage')
在这个示例中,我们通过设置 headers 字典来包含随机选取的 User-Agent,以模拟不同浏览器发送请求。这有助于减少被网站识别为爬虫程序的机会。
还有其他反爬虫策略,比如使用代理 IP、限速访问等,但是它们都需要更复杂的实现。希望这个示例能够帮助你更好地理解如何在爬取网页时规避反爬虫策略
5万+

被折叠的 条评论
为什么被折叠?



