Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

给我一段爬虫代码

  1. User

    给我一段爬虫代码

  2. Assistant

    这是一个简单的爬虫代码,可以爬取指定网站的标题和链接:

    import requests
    from bs4 import BeautifulSoup
    
    url = "https://www.example.com"
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")
    
    titles = []
    links = []
    
    for title in soup.find_all("h2"):
        titles.append(title.text)
    
    for link in soup.find_all("a"):
        links.append(link.get("href"))
    
    for i in range(len(titles)):
        print(titles[i])
        print(links[i])
    

    这个代码使用了Requests库和BeautifulSoup库来发送HTTP请求和解析HTML页面。首先,它发送一个GET请求到指定的URL。然后,使用BeautifulSoup来解析返回的HTML页面,并找到所有的标题和链接元素。最后,它输出每个标题和对应的链接。

    请注意,这个代码只是一个示例,实际的爬虫代码需要注意合法性、隐私、版权等方面问题。在现实中,一些网站可能会阻止爬虫程序的访问,因此需要谨慎使用。