溫馨提示×

python爬蟲怎么遍歷網頁

小億
253
2024-01-09 12:04:38
欄目: 編程語言

在Python中,可以使用多種方式遍歷網頁,以下是兩種常見的方法:

  1. 使用requests和BeautifulSoup庫:首先,使用requests庫發送HTTP請求獲取網頁的HTML內容,然后使用BeautifulSoup庫解析HTML內容??梢允褂肂eautifulSoup提供的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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女