python系列30:各种爬虫技术总结

1. 使用requests获取网页内容

以巴鲁夫产品为例,可以用get请求获取内容:

https://www.balluff.com.cn/zh-cn/products/BES02YF

对应的网页为:

使用简单方法进行解析即可

复制代码
import requests
r = 'BES02YF'
res = requests.get("https://www.balluff.com.cn/zh-cn/products/%s"%r).text
result = res.split("</title>")[0].split("<title>")[1]

2. 添加多进程

使用multiprocessing进行加速,以上面的balluff为例:

复制代码
from multiprocessing.dummy import Pool as ThreadPool
from tqdm import tqdm
import numpy as np
import os,json,requests,base64,struct
data = pd.read_excel("balluff.xlsx",sheet_name='all')
valuelist = list(data['Type'])
def getf(type_value):
    try:
        res = requests.get("https://www.balluff.com.cn/zh-cn/products/%s"%type_value).text
        return res.split("</title>")[0].split("<title>")[1]
    except:
        return None
results = []
with ThreadPool(100) as p:
    results = list(tqdm(p.imap(getf, valuelist), total=len(valuelist)))

3. 加入header

有一些网站有防爬虫的功能,需要在请求中添加header,例如西门子的网站需要用如下的方法:

复制代码
def getf(type_value):
    try:
        headers = {"user-agent": "Mizilla/5.0"}
        res = requests.get("""https://mall.industry.siemens.com/mall/zh/CN/Catalog/Product/?mlfb=%s&SiepCountryCode=CN"""%type_value,headers=headers).text.split("""productIdentifier""")[1]
        return res.split("""</span>""")[0].split('>')[-1]
    except:
        return None

4. 使用selenium

以festo为例,会很讨厌的弹出对话框。

我们使用selenium模拟点击。并且用find_element找到元素:

复制代码
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('https://www.festo.com.cn/cn/zh/search/?text=548755')
f1=driver.find_element(By.PARTIAL_LINK_TEXT,'接受')
f1.click()
from tqdm import tqdm
r1 = []
r2 = []
for type_value in tqdm(valuelist):
    try:
        driver.get('https://www.festo.com.cn/cn/zh/search/?text=%s'%type_value)
        time.sleep(1)
        r1.append(driver.find_element(By.CLASS_NAME,'product-code--NjIDg').text)
        try:
            r2.append(driver.find_element(By.CLASS_NAME,'ident-code--qx13c').text)
        except:
            r2.append(driver.find_element(By.CLASS_NAME,'product-order-code--TR15s').text)
    except:
        r1.append(None)
        r2.append(None)

5. 获取真实的requests地址

以keyence为例,查看网页源代码是无法获得产品清单的,需要在chrome的开发者工具中点击Network,选择Fetch/XHR,然后刷新页面,找到Type为fetch的链接:

链接为/data/api/seriesModels?siteID=21&languageID=zh-CN&groupID=tcm%3A115-347504&typeID=tcm%3A115-347487&seriesID=WS_SR_fu,其中groupID开始的部分,可以从源代码中获得。具体代码为:

复制代码
import json
from tqdm import tqdm
result = []
for r2i in tqdm(r2):
    result += json.loads(requests.get('https://www.keyence.com.cn/data/api/seriesModels?siteID=21&languageID=zh-CN&'+\
    list(filter(lambda x:'prd-seriesFooter-navLink of-support' in x,requests.get(r2i)\
    .text.split('\n')))[0].split('?')[1].split('&modelId')[0].replace('Id','ID')).text)['models']

如果找到的链接过于难处理(比如post请求带着一堆请求体),那可以直接右键,选择copy->copy curl,然后替换其中的关键字,用命令行执行即可。

相关推荐
froginwe113 分钟前
Maven 仓库概述
开发语言
我不是QI11 分钟前
周志华《机器学习---西瓜书》 一
人工智能·python·机器学习·ai
今天没ID12 分钟前
Python 编程实战:从基础语法到算法实现 (1)
python
二川bro36 分钟前
Python在AI领域应用全景:2025趋势与案例
开发语言·人工智能·python
棒棒的皮皮1 小时前
【Python】Open3d用于3D测高项目
python·3d·open3d
CoderYanger1 小时前
优选算法-队列+宽搜(BFS):72.二叉树的最大宽度
java·开发语言·算法·leetcode·职场和发展·宽度优先·1024程序员节
CodeLongBear1 小时前
Python数据分析: 数据可视化入门:Matplotlib基础操作与多坐标系实战
python·信息可视化·数据分析
疏狂难除1 小时前
随便玩玩lldb (二)
开发语言·后端·rust
星轨初途1 小时前
数据结构排序算法详解(5)——非比较函数:计数排序(鸽巢原理)及排序算法复杂度和稳定性分析
c语言·开发语言·数据结构·经验分享·笔记·算法·排序算法
b***65322 小时前
GO 快速升级Go版本
开发语言·redis·golang