要编写Python网络爬虫,您可以使用一些流行的库,如Requests和BeautifulSoup。以下是一个简单的网络爬虫示例,用于抓取网站上的标题和链接:
首先,确保您已经安装了所需的库。在命令行中运行以下命令来安装它们:
pip install requests beautifulsoup4
接下来,创建一个名为simple_crawler.py的文件,并在其中编写以下代码:
import requests
from bs4 import BeautifulSoup
def get_page(url):
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
print(f"Error: Unable to fetch the page. Status code: {response.status_code}")
return None
def parse_page(html):
soup = BeautifulSoup(html, "html.parser")
titles = soup.find_all("h2") # 根据网站中标题的标签进行修改
links = soup.find_all("a")
for title, link in zip(titles, links):
print(title.get_text(), link["href"])
def main():
url = input("Enter the URL of the website you want to crawl: ")
html = get_page(url)
if html:
parse_page(html)
if __name__ == "__main__":
main()
这个简单的网络爬虫首先从用户那里获取要抓取的网站URL,然后使用Requests库获取页面的HTML内容。接下来,它使用BeautifulSoup解析HTML,并提取所有标签的文本(这通常是标题)和所有标签的href属性(这通常是链接)。最后,它打印出提取到的标题和链接。
请注意,这个示例仅适用于具有特定HTML结构的网站。要使其适用于其他网站,您需要根据目标网站的HTML结构修改parse_page函数中的代码。您可以使用浏览器的开发者工具(按F12打开)来检查页面元素并找到正确的标签和属性。
以上就是关于“python网络爬虫怎样写代码”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm