阅读量:3
这是一个简单的Python爬虫代码示例,使用了requests和BeautifulSoup库来获取网页内容并解析:
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())
if __name__ == "__main__":
url = "https://example.com" # 替换为你要爬取的网址
html = get_html(url)
if html:
parse_html(html)
请注意,这个示例仅适用于特定的网页结构(这里使用了标签)。你需要根据你要爬取的网页的实际HTML结构来修改parse_html函数中的代码。
在使用此代码之前,请确保已经安装了requests和beautifulsoup4库。如果没有安装,可以使用以下命令安装:
pip install requests beautifulsoup4
此外,根据你要爬取的网站的robots.txt文件和使用条款,请确保你的爬虫行为符合相关规定。
以上就是关于“简单的python爬虫代码怎么写”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm