【问题标题】:How to open with urllib, link parsed by BeautifulSoup?如何用urllib打开,BeautifulSoup解析的链接?
【发布时间】: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


    【解决方案1】:

    应该只是对您的链接进行urlencoding。

    link = "https://example.com" + urllib.parse.quote(total.find('a').get('href'))

    【讨论】:

    • 这可能适用于 python2,但这是 python3 并且给了我一个错误:TypeError: 'module' object is not callable。实际上 urllib.parse.urlunparse 也不起作用。
    • 那也行不通。请参阅链接示例。 urllib.parse.quote 也编码 %2F 符号,但它们不应该。 Firefox 也会解析此链接。
    猜你喜欢
    • 2016-01-28
    • 2013-04-01
    • 1970-01-01
    • 2013-04-07
    • 2019-06-13
    • 1970-01-01
    • 2015-03-07
    • 2020-07-15
    • 1970-01-01
    相关资源
    最近更新 更多