【发布时间】:2015-12-23 11:10:04
【问题描述】:
我使用 python 3、Beautiful Soup 4 和 urllib 来解析一些 html。 我需要解析一些页面,从这些页面获取一些链接,然后从这些链接中解析页面。我尝试这样做:
import urllib.request
import urllib
from bs4 import BeautifulSoup
with urllib.request.urlopen("https://example.com/mypage?myparam=%D0%BC%D0%B2") as response:
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
total = soup.find(attrs={"class":"item_total"})
link = u"https://example.com" + total.find('a').get('href')
with urllib.request.urlopen(link) as response:
exthtml = BeautifulSoup(html,response.read())
但是 urllib 无法打开第二个链接,因为它没有编码,就像第一个链接一样。它有不同的语言符号和空格。 我尝试对 url 进行编码,例如:
link = urllib.parse.quote("https://example.com" + total.find('a').get('href'))
但它对所有符号进行编码。如何获取正确的 url form bs,并获取请求?
更新: 第二个链接的例子,由
导致link = u"https://example.com" + total.find('a').get('href')
是
"https://example.com/mypage?p1url=www.example.net%2Fthatpage%2F01234&text=абвгд еёжз ийклмно"
【问题讨论】:
标签: python python-3.x beautifulsoup urllib