python爬虫如何写,有哪些成功爬取的案例

编写Python爬虫时,常用的库包括Requests、Beautiful Soup和Scrapy。以下是三个简单的Python爬虫案例,分别使用Requests和Beautiful Soup,以及Scrapy。

1. 使用Requests和Beautiful Soup爬取网页内容:

python 复制代码
import requests
from bs4 import BeautifulSoup

url = "https://example.com"
response = requests.get(url)

if response.status_code == 200:
    soup = BeautifulSoup(response.text, 'html.parser')
    # 在这里可以使用Beautiful Soup提取页面内容
    # 例如:titles = soup.find_all('h2')
    print(soup.title.text)
else:
    print(f"Failed to retrieve the page. Status code: {response.status_code}")

2. 使用Requests和正则表达式爬取图片:

python 复制代码
import requests
import re
from urllib.parse import urljoin

url = "https://example.com"
response = requests.get(url)

if response.status_code == 200:
    image_urls = re.findall(r'<img.*?src=["\'](.*?)["\']', response.text)
    for img_url in image_urls:
        full_url = urljoin(url, img_url)
        # 在这里可以下载图片或进行其他处理
        # 例如:response = requests.get(full_url); save_image(response.content, "image.jpg")
        print(full_url)
else:
    print(f"Failed to retrieve the page. Status code: {response.status_code}")

3. 使用Scrapy爬取网站:

首先,确保已安装Scrapy:

bash 复制代码
pip install scrapy

创建一个新的Scrapy项目:

bash 复制代码
scrapy startproject myproject
cd myproject

编辑Spider:

python 复制代码
# myproject/spiders/myspider.py
import scrapy

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

    def parse(self, response):
        # 在这里可以使用XPath或CSS选择器提取数据
        # 例如:titles = response.xpath('//h2/text()').getall()
        title = response.css('title::text').get()
        print(title)

运行Scrapy爬虫:

bash 复制代码
scrapy crawl myspider

这些例子只是入门,实际项目中可能需要处理更多的异常情况、使用代理、设置请求头等。爬取网页时,请确保遵守网站的Robots.txt文件和使用者协议。

相关推荐
Irene19911 分钟前
Python 中的 round() 函数不是严格的“四舍五入“,而是采用银行家舍入法(Bankers‘ Rounding)
python
ZC跨境爬虫1 分钟前
3D 地球卫星轨道可视化平台开发 Day9(AI阈值调控+小众卫星识别+低Token测试模式实战)
人工智能·python·3d·信息可视化·json
2301_813599553 分钟前
CSS中relative与absolute的区别_详解相对与绝对定位应用场景
jvm·数据库·python
qq_3721542312 分钟前
c++怎么在写入文件流时通过peek预读功能实现复杂的逻辑判断【实战】
jvm·数据库·python
m0_5145205721 分钟前
CSS如何给按钮添加按下缩小的动画_利用-active配合transform
jvm·数据库·python
yejqvow1222 分钟前
CSS如何制作加载时的点点点跳动效果_使用animation循环延迟
jvm·数据库·python
2401_8359568123 分钟前
CSS如何解决CSS引入后的样式覆盖_理解优先级原则避免重写
jvm·数据库·python
小猪皮蛋粥27 分钟前
python画图
开发语言·python
m0_5887584828 分钟前
CSS如何创建三角箭头图标_通过border透明技巧实现
jvm·数据库·python
小白学大数据33 分钟前
解决 Python 爬虫被限制:延迟抓取指令深度解析
开发语言·c++·爬虫·python