首页 > 编程知识 正文

Python爬虫的多种方法

时间:2023-11-22 01:18:58 阅读:302941 作者:PWCU

本文将从多个方面详细阐述Python爬虫的多种方法。

一、基础爬虫

1、使用urllib库发送HTTP请求,获取网页内容。

import urllib.request

url = "http://www.example.com"
response = urllib.request.urlopen(url)
html_content = response.read().decode("utf-8")
print(html_content)

2、使用BeautifulSoup库解析网页内容,提取所需数据。

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_content, "html.parser")
title = soup.title.string
print(title)

二、动态网页爬虫

1、使用Selenium库模拟浏览器行为,加载JavaScript渲染的页面。

from selenium import webdriver

driver = webdriver.Chrome()
driver.get(url)
html_content = driver.page_source
print(html_content)
driver.quit()

2、使用Selenium库定位DOM元素,提取所需数据。

from selenium.webdriver.common.by import By

element = driver.find_element(By.XPATH, "//div[@class='content']")
data = element.text
print(data)

三、API接口爬虫

1、使用requests库发送HTTP请求,获取API接口的响应数据。

import requests

url = "http://api.example.com/data"
response = requests.get(url)
json_data = response.json()
print(json_data)

2、解析JSON数据,提取所需字段。

data = json_data["data"]
print(data)

四、分布式爬虫

1、使用Scrapy框架进行分布式爬虫。参考Scrapy官方文档。

# scrapy.cfg

[settings]
scrapy_redis.start_urls_key = myspider:start_urls
scrapy_redis.scheduler.queue_key = myspider:requests
scrapy_redis.scheduler.dupefilter_key = myspider:dupefilter

[spider]
redis_host = localhost
redis_port = 6379

2、配置Redis用于存储爬虫的请求队列、去重队列和爬取结果。

# settings.py

SCHEDULER = "scrapy_redis.scheduler.Scheduler"
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
REDIS_HOST = "localhost"
REDIS_PORT = 6379

五、数据存储

1、使用MySQL数据库存储爬取的数据。

import pymysql

conn = pymysql.connect(host="localhost", user="root", password="password", database="mydb")
cursor = conn.cursor()
sql = "INSERT INTO table_name (column1, column2) VALUES (%s, %s)"
cursor.execute(sql, (value1, value2))
conn.commit()
cursor.close()
conn.close()

2、使用MongoDB数据库存储爬取的数据。

from pymongo import MongoClient


client = MongoClient("mongodb://localhost:27017/")
db = client["mydb"]
collection = db["mycollection"]
data = {"key": "value"}
collection.insert_one(data)

六、反反爬虫

1、设置请求头信息,伪装成浏览器进行访问。

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"
}
response = requests.get(url, headers=headers)

2、使用代理IP进行请求,避免被网站封禁。

proxies = {
    "http": "http://10.10.1.10:3128",
    "https": "http://10.10.1.10:1080"
}
response = requests.get(url, proxies=proxies)

七、其他注意事项

1、遵守网站的Robots协议,不要对不允许爬取的页面进行访问。

2、设置适当的爬取间隔,避免给网站服务器带来过大的负担。

以上是Python爬虫的多种方法的详细阐述。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。