温馨提示×

python爬虫怎么遍历网页

小亿
139
2024-01-09 12:04:38
栏目: 编程语言

在Python中,可以使用多种方式遍历网页,以下是两种常见的方法:

  1. 使用requests和BeautifulSoup库:首先,使用requests库发送HTTP请求获取网页的HTML内容,然后使用BeautifulSoup库解析HTML内容。可以使用BeautifulSoup提供的find_all()方法遍历网页上特定的标签或元素。
import requests
from bs4 import BeautifulSoup

# 发送HTTP请求获取网页内容
response = requests.get('http://example.com')
html_content = response.text

# 解析HTML内容
soup = BeautifulSoup(html_content, 'html.parser')

# 遍历网页上的所有链接
for link in soup.find_all('a'):
    print(link.get('href'))
  1. 使用Scrapy库:Scrapy是一个功能强大的Python爬虫框架,它提供了一套完整的爬取、处理和存储网页数据的工具和方法。通过编写自定义的Spider,可以遍历网页上的各个链接和页面。
import scrapy

class MySpider(scrapy.Spider):
    name = 'example'
    start_urls = ['http://example.com']

    def parse(self, response):
        # 遍历网页上的所有链接
        for link in response.css('a::attr(href)').getall():
            yield {
                'link': link
            }

以上是两种常见的方法,根据具体的需求选择合适的方式进行网页遍历。

0