ulsoap和Urllib2未正确提取数据

2024-04-26 04:33:55 发布

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

我正在使用以下代码,尝试在Python变量中获取所有网站数据,以便将数据提取到mongodb。你知道吗

url = "<url>"
page = urllib2.urlopen(url)
html = page.read()

print(html)

soup = BeautifulSoup(page, 'html.parser')

soap/page变量中存储的内容只是HTML布局,包括嵌套的js脚本。你知道吗

为什么不提供实际的网站数据?你知道吗


Tags: 数据代码parserurlread网站mongodbhtml
1条回答
网友
1楼 · 发布于 2024-04-26 04:33:55

问题解决了。这与Python库本身无关,而是身份验证问题。你知道吗

我用来解决这个问题的代码是:

username = "xxx"
password = "yyy"

command = "curl -X GET -u \"" + username + ":" + password +  "\" " + url 
request  = urllib2.Request(url)
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)

response = urllib2.urlopen(request, timeout=20)
result = response.read()
soup = BeautifulSoup(result, 'html.parser')
prettified = soup.prettify().encode("utf-8")

相关问题 更多 >