python

怎么用python写一个简单的爬虫

小亿
83
2024-12-07 07:01:32
栏目: 编程语言

要用Python编写一个简单的爬虫,你可以使用requests库来获取网页内容,然后使用BeautifulSoup库来解析HTML并提取所需信息。以下是一个简单的示例,用于抓取网站上的标题和链接:

首先,确保你已经安装了requests和beautifulsoup4库。如果没有,请使用以下命令安装:

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(f"Title: {title.get_text().strip()}")
        print(f"Link: {link['href']}")
        print()

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()

将代码中的h2a标签替换为你要抓取的网站结构的相应标签。运行simple_crawler.py文件,然后输入要抓取的网站URL。程序将输出页面上的标题和链接。

请注意,这只是一个简单的示例,实际爬虫可能需要处理更复杂的情况,例如处理分页、登录、JavaScript渲染的页面等。对于更高级的爬虫,可以考虑使用Scrapy框架。

0
看了该问题的人还看了