网页抓取:HTTPError:HTTP Error 403:禁止,python3

2024-09-24 20:39:00 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨我需要废网页结束提取数据id使用正则表达式

这是我的代码:

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("https://clarity-project.info/tenders/?entity=38163425&offset=100")
bsObj = BeautifulSoup(html,"html.parser")
DataId = bsObg.findAll("data-id", {"skr":re.compile("data-id=[0-9,a-f]")})
for DataId in DataId:
    print(DataId["skr"])

当我在Jupyter中运行程序时:

^{pr2}$

Tags: 数据代码fromimportid网页datarequest
3条回答

看起来web服务器要求您在向Python的urllib提供内容之前进行身份验证。但是,它们整齐地为wget和{}和{a1}似乎不存在,所以我认为这样的刮擦对它们来说是可以的。不过,最好先问问他们。在

至于代码,简单地将用户代理字符串更改为他们更喜欢的字符串似乎可以奏效:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from urllib.request import urlopen, Request

request = Request(
    'https://clarity-project.info/tenders/?entity=38163425&offset=100',
    headers={
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0'})

html = urlopen(request).read().decode()

(无关,您的代码中有另一个错误:bsObj≠bsObg)

编辑在下面添加代码,以回答评论中的其他问题:

您似乎需要找到dataid属性的值,而不管它属于哪个标记。下面的代码就是这样做的:

^{pr2}$

关键是简单地使用lambda表达式作为BeautifulSoup的findAll函数的参数。在

你可以试试这个:

#!/usr/bin/env python

from bs4 import BeautifulSoup
import requests 

url = 'your url here'
soup = BeautifulSoup(requests.get(url).text,"html.parser")

for i in soup.find_all('tr', attrs={'class':'table-row'}):
    print '[Data id] => {}'.format(i.get('data-id'))

这应该行得通!在

由于默认用户代理,服务器可能会阻止您的请求。您可以更改此设置,以便在服务器上显示为web浏览器。例如,Chrome用户代理是:

Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36 

若要添加用户代理,可以创建一个请求对象,其中url作为参数,用户代理作为关键字参数“headers”传入词典。在

参见:

^{pr2}$

相关问题 更多 >