python爬蟲怎么遍歷網(wǎng)頁(yè)

小億
190
2024-01-09 12:04:38

在Python中,可以使用多種方式遍歷網(wǎng)頁(yè),以下是兩種常見的方法:

  1. 使用requests和BeautifulSoup庫(kù):首先,使用requests庫(kù)發(fā)送HTTP請(qǐng)求獲取網(wǎng)頁(yè)的HTML內(nèi)容,然后使用BeautifulSoup庫(kù)解析HTML內(nèi)容??梢允褂肂eautifulSoup提供的find_all()方法遍歷網(wǎng)頁(yè)上特定的標(biāo)簽或元素。
import requests
from bs4 import BeautifulSoup

# 發(fā)送HTTP請(qǐng)求獲取網(wǎng)頁(yè)內(nèi)容
response = requests.get('http://example.com')
html_content = response.text

# 解析HTML內(nèi)容
soup = BeautifulSoup(html_content, 'html.parser')

# 遍歷網(wǎng)頁(yè)上的所有鏈接
for link in soup.find_all('a'):
    print(link.get('href'))
  1. 使用Scrapy庫(kù):Scrapy是一個(gè)功能強(qiáng)大的Python爬蟲框架,它提供了一套完整的爬取、處理和存儲(chǔ)網(wǎng)頁(yè)數(shù)據(jù)的工具和方法。通過(guò)編寫自定義的Spider,可以遍歷網(wǎng)頁(yè)上的各個(gè)鏈接和頁(yè)面。
import scrapy

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

    def parse(self, response):
        # 遍歷網(wǎng)頁(yè)上的所有鏈接
        for link in response.css('a::attr(href)').getall():
            yield {
                'link': link
            }

以上是兩種常見的方法,根據(jù)具體的需求選擇合適的方式進(jìn)行網(wǎng)頁(yè)遍歷。

0