阅读量:2
要编写一个简单的Python网页爬虫,您可以使用requests库来获取网页内容,然后使用BeautifulSoup库来解析HTML并提取所需的信息。以下是一个示例代码:
import requests
from bs4 import BeautifulSoup
def get_html(url):
try:
response = requests.get(url)
response.raise_for_status()
response.encoding = response.apparent_encoding
return response.text
except Exception as e:
print(f"获取网页失败: {e}")
return None
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
titles = soup.find_all('h2', class_='title') # 根据网页结构选择合适的标签和类名
for title in titles:
print(title.get_text())
def main():
url = 'https://example.com' # 替换为您要爬取的网址
html = get_html(url)
if html:
parse_html(html)
if __name__ == '__main__':
main()
在这个示例中,我们首先导入requests和BeautifulSoup库。然后,我们定义了两个函数:get_html()用于获取指定URL的HTML内容,parse_html()用于解析HTML并打印所有找到的标题(这里假设标题被包含在标签中)。最后,我们在main()函数中调用这两个函数来完成整个爬虫的工作。
请注意,您需要根据目标网站的HTML结构来调整parse_html()函数中的代码,以确保正确提取所需的信息。此外,如果目标网站有反爬虫措施,您可能还需要设置请求头、使用代理IP或实施其他策略来避免被封禁。
以上就是关于“网页爬虫代码python怎么写”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm