用python写一个爬虫

女爷i 2024-03-27 12:47 219阅读 0赞

可以使用 Python 的第三方库 requestsBeautifulSoup 来编写一个爬虫。

首先,需要安装这两个库,可以使用 pip 命令来安装:

  1. pipinstall requests
  2. pip install beautifulsoup4

然后,可以使用 requests 库来发送 HTTP 请求,获取网页内容。例如:

  1. import requests
  2. url = 'http://example.com'
  3. response = requests.get(url)
  4. html = response.text

接着,可以使用 BeautifulSoup 库来解析 HTML 文本,提取你感兴趣的信息。例如:

  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'html.parser')
  3. # 提取所有的链接
  4. links = soup.find_all('a')
  5. for link in links:
  6. print(link.get('href'))

完整的爬虫代码可能长这样:

  1. import requests
  2. from bs4 import BeautifulSoup
  3. def crawl(url):
  4. # 发送 HTTP 请求,获取响应内容
  5. response = requests.get(url)
  6. html = response.text
  7. # 解析 HTML,提取信息
  8. soup = BeautifulSoup(html, 'html.parser')
  9. links = soup.find_all('a')
  10. # 处理每个链接
  11. for link in links:
  12. href = link.get('href')
  13. # 对链接进行处理,提取有效信息
  14. print(href)
  15. if __name__ == '__main__':
  16. crawl('http://example.com')

注意:在编写爬虫时,要遵守网站的 robots.txt 文件,不要对网站进行滥用或者恶意攻击。

发表评论

表情:
评论列表 (有 0 条评论,219人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python一个爬虫

    可以使用 Python 的第三方库 `requests` 和 `BeautifulSoup` 来编写一个爬虫。 首先,需要安装这两个库,可以使用 `pip` 命令来安装: