如何用Python编写简单的网络爬虫(页面代码简单分析过程)
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
import requests
from bs4 import BeautifulSoup
def get_html(url):
"""发送HTTP请求,获取网页HTML内容"""
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
return None
except requests.RequestException:
return None
def parse_html(html):
"""解析HTML,提取有效信息"""
soup = BeautifulSoup(html, 'html.parser')
# 假设我们要提取所有的段落文本
paragraphs = soup.find_all('p')
return [p.get_text() for p in paragraphs]
def main():
url = 'http://example.com' # 替换为你想爬取的网页URL
html = get_html(url)
if html:
parsed_data = parse_html(html)
for data in parsed_data:
print(data)
else:
print("Failed to retrieve the webpage")
if __name__ == '__main__':
main()
这段代码展示了如何使用Python的requests库来发送HTTP请求,以及如何使用BeautifulSoup库来解析HTML并提取数据。这是一个简单的网络爬虫示例,可以根据实际需求进行功能扩展。
评论已关闭