Python爬虫:一些常用的爬虫技巧总结_python爬虫常用的技术
warning:
这篇文章距离上次修改已过229天,其中的内容可能已经有所变动。
import requests
from bs4 import BeautifulSoup
def download_webpage(url):
"""下载网页内容"""
headers = {
'User-Agent': 'Mozilla/5.0',
'Accept-Encoding': 'gzip, deflate',
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
else:
return None
def parse_soup(soup):
"""解析BeautifulSoup对象"""
# 示例解析:提取所有的段落文本
paragraphs = soup.find_all('p')
texts = [p.get_text() for p in paragraphs]
return texts
def main():
url = 'https://example.com'
html = download_webpage(url)
soup = BeautifulSoup(html, 'html.parser')
parsed_data = parse_soup(soup)
print(parsed_data)
if __name__ == '__main__':
main()
这段代码展示了如何使用Python的requests库下载网页内容,以及如何使用BeautifulSoup库解析HTML。在download_webpage
函数中,我们添加了必要的请求头User-Agent
和Accept-Encoding
,模拟浏览器行为,避免被服务器识别并拒绝请求。parse_soup
函数中提供了一个示例,展示了如何提取段落文本,开发者可以根据需要进行相应的信息提取。
评论已关闭