Python 网络爬虫
import requests
from bs4 import BeautifulSoup
def get_html(url):
"""发送HTTP请求,获取网页内容"""
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
return "页面无法访问"
except requests.RequestException:
return "发生错误"
def parse_html(html):
"""解析网页,提取有效信息"""
soup = BeautifulSoup(html, 'html.parser')
# 假设我们要提取所有的段落文本
paragraphs = soup.find_all('p')
return [p.get_text() for p in paragraphs]
def main():
url = "https://example.com" # 替换为你想爬取的网页
html = get_html(url)
paragraphs = parse_html(html)
for p in paragraphs:
print(p)
if __name__ == "__main__":
main()
这段代码展示了如何使用Python的requests库发送HTTP请求以获取网页内容,并使用BeautifulSoup库解析HTML,提取所有段落文本。在实际应用中,你需要根据目标网站的结构调整解析代码,以提取你需要的数据。
评论已关闭