Python 绕过arrow/kynix/digikey/mouser/avnet/newark 403状态(TLS/JA3)反爬

Scrapy downloaderMiddlewares

pip install curl_cffi
pip install pyhttpx

downloaderMiddlewares.py

import requests, pyhttpx, random
from curl_cffi import requests as cffi_requests

impersonates = ["chrome99", "chrome101", "chrome107", "chrome110", "edge99", "edge101"]
proxy = {
        'PROXY_USER': "xxx",
        'PROXY_PASS': "xxx",
        'PROXY_SERVER': "http://ip:port"
    }

def get_proxys():
    proxy_host = proxy.get('PROXY_SERVER').rsplit(
        ':', maxsplit=1)[0].split('//')[-1]
    proxy_port = proxy.get('PROXY_SERVER').rsplit(':', maxsplit=1)[-1]
    proxy_username = proxy.get('PROXY_USER')
    proxy_pwd = proxy.get('PROXY_PASS')
    proxyMeta = "http://%(user)s:%(pass)s@%(host)s:%(port)s" % {
        "host": proxy_host,
        "port": proxy_port,
        "user": proxy_username,
        "pass": proxy_pwd,
    }
    proxies = {
        'http': proxyMeta,
        'https': proxyMeta,
    }
    return proxies

def bypass_ja3_get(url, headers, proxies, timeout=15, data={}):
    resp = None
    try:
        sess1 = requests.session()
        sess1.headers = headers
        sess1.proxies = proxies
        resp = sess1.get(url, data=data, allow_redirects=False, timeout=timeout)
        print('sess1: ', resp.status_code)
        if resp.status_code != 200: raise TimeoutError
    except:
        try:
            sess2 = pyhttpx.HttpSession(browser_type='chrome', http2=True)
            resp = sess2.get(url, proxies=proxies, allow_redirects=False, timeout=timeout)
            print('sess2: ', resp.status_code)
            if resp.status_code != 200: raise TimeoutError
        except:
            try:
                sess3 = cffi_requests.Session()
                resp = sess3.get(url, proxies=proxies, impersonate=random.choice(impersonates), timeout=timeout)
                print('sess3: ', resp.status_code)
            except:
                pass
    return resp

class ByPassJa3RequestMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.
    def __init__(self):
        self.headers = {
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'no-cache',
            'pragma': 'no-cache',
            'upgrade-insecure-requests': '1',
            'user-agent': '',
            'Connection': 'close'
        }

    @defer.inlineCallbacks
    def process_request(self, request, spider):
        container=[]
        out = defer.Deferred()
        reactor.callInThread(self._get_res, request, container, out, spider)
        yield out
        if len(container)>0: defer.returnValue(container[0])

    def _get_res(self,request,container,out,spider):
        try:
            url= request.url
            meta = request.meta
            proxies= meta.get('proxy')
            if request.headers: self.headers= {k.decode():v[0].decode() for k, v in request.headers.items()}
            r = utils.bypass_ja3_get(url, self.headers, proxies)
            print('{} StatusCode: '.format(spider.name), r.status_code)
            resp = Response(url=url,status=r.status_code,body=r.content,encoding=r.encoding,request=request)
            container.append(resp)
            reactor.callFromThread(out.callback, resp)
        except Exception as e:
            print('{} Error: '.format(spider.name), e)
            err=str(type(e))+' '+str(e)
            reactor.callFromThread(out.errback, ValueError(err))

spider.py

custom_settings['DOWNLOADER_MIDDLEWARES'] = {
   'Material.middlewares.downloaderMiddlewares.ByPassJa3RequestMiddleware': 400,
}

yield scrapy.Request(url, meta={'proxy': utils.get_proxys(self.proxy)}, callback=self.parse_data, errback=self.errback_response)
  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 我可以帮你写一段Python代码来抓取DigiKey的列表,它将从DigiKey的网站抓取某一页面的所有产品列表,并将其存储在一个列表中:import requests from bs4 import BeautifulSoupurl = "https://www.digikey.com/products/en"response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser")products = soup.find_all("div", {"class": "m-catalog-listing__product"})product_list = [] for product in products: product_name = product.find("span", {"class": "m-catalog-listing__product-title"}).text product_list.append(product_name)print(product_list) ### 回答2: 使用Python编写Digikey列表的采集可以使用BeautifulSoup库来实现。 首先,我们需要安装BeautifulSoup库。可以通过在终端运行以下命令来安装: ``` pip install beautifulsoup4 ``` 接下来,我们可以使用以下代码示例来实现Digikey列表的采集: ``` import requests from bs4 import BeautifulSoup # 设置目标url url = "https://www.digikey.com/products/en/integrated-circuits-ics/logic-gates-and-inverters/716" # 发送get请求 response = requests.get(url) # 解析网页内容 soup = BeautifulSoup(response.text, "html.parser") # 定位特定标签 product_list = soup.find_all("product-name") # 遍历产品列表 for product in product_list: # 获取产品名称并打印 print(product.text.strip()) ``` 在上述代码中,我们首先导入了requests库和BeautifulSoup库。然后,我们设置了我们要采集的Digikey列表的URL。之后,我们发送了一个GET请求来获取网页的内容。接下来,我们使用BeautifulSoup库对网页进行解析,定位特定的标签(在这个例子中我们使用了`product-name`标签),然后遍历列表并打印出产品的名称。 请注意,以上代码只是一个简单的示例,根据Digikey网站的结构和需要采集的信息,可能需要进行进一步的调整和修改。在实际使用中,可能需要处理虫措施、翻页、登录等问题。 ### 回答3: Python 是一种功能强大的编程语言,它提供了一系列库和工具,可以用来编写各种类型的脚本和应用程序。要编写一个 Digi-Key 的列表采集脚本,可以使用 Python 中的 requests 和 BeautifulSoup 库。 首先,需要使用 requests 库发送 HTTP 请求,获取 Digi-Key 网页的内容。可以使用 requests.get() 函数来发送 GET 请求,并将返回的响应保存在一个变量中。 接下来,使用 BeautifulSoup 库解析网页内容。可以使用 BeautifulSoup() 函数将网页内容传递给 BeautifulSoup 对象,并指定解析器类型。然后,可以使用 BeautifulSoup 对象的 find() 或 find_all() 方法来查找特定的元素或标签,提取所需的数据。 对于 Digi-Key 的列表采集,例如要获取产品的名称、价格和库存信息,可以通过检查网页的 HTML 结构,找到相应的元素或标签,并使用 BeautifulSoup 来提取这些数据。具体的解析逻辑取决于 Digi-Key 网页的结构和所需的数据。 最后,可以将提取的数据保存到一个列表或以其他形式进行处理和展示。 以下是一个示例代码的简单框架: ```python import requests from bs4 import BeautifulSoup # 发送请求 response = requests.get("Digi-Key 网页的 URL") # 解析网页内容 soup = BeautifulSoup(response.text, "html.parser") # 查找并提取数据 product_name = soup.find("div", class_="product-name").text price = soup.find("div", class_="price").text stock = soup.find("div", class_="stock").text # 打印提取的数据 print("产品名称:", product_name) print("价格:", price) print("库存:", stock) ``` 需要注意的是,实际编写一个完整的 Digi-Key 列表采集脚本可能需要更多的处理和逻辑,包括处理分页、处理异常情况等。这只是一个简单的示例,读者可以根据具体需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值