【问题标题】:Scraping site returns different href for a link抓取网站为链接返回不同的href
【发布时间】:2019-03-18 23:03:32
【问题描述】:

在python 中,我使用requests 模块和BS4 来通过duckduckgo.com 搜索网络。我手动转到http://duckduckgo.com/html/?q='hello',并使用开发工具获得了第一个结果标题为<a class="result__a" href="http://example.com">。现在我使用以下代码通过 Python 获取 href:

html = requests.get('http://duckduckgo.com/html/?q=hello').content
soup = BeautifulSoup4(html, 'html.parser')
result = soup.find('a', class_='result__a')['href']

但是,href 看起来像乱码,与我手动看到的完全不同。知道为什么会这样吗?

【问题讨论】:

  • 您能否也添加您正在接受的“乱码”href?
  • "/l/?kh=-1&uddg=https%3A%2F%2Fwww.example.com"
  • 这是真的。您想要的第一个链接是:<a rel="nofollow" class="result__a" href="http://duckduckgo.com/y.js?u3=https%3A%2F%2Fr.search.yahoo.com%2Fcbclk%2FdWU9MUEwOUNCRUYzMUQzNEUzNSZ1dD0xNTM5NTA4NTEzNTc4JnVvPTc3NDQ2ODg3ODA1MTQ4Jmx0PTImZXM9ZVVTaDk0UUdQUzliS0hRLQ%2D%2D%2FRV%3D2%2FRE%3D1539537313%2FRO%3D10%2FRU%3Dhttps%253a%252f%252fwww.bing.com%252faclick%253fld%253dd3jIjIFx8mbuUuyzqoWL4HCjVUCUygBhbi7LdfVaC2QTd8kHOx2WK7iOznJVD1yYosHtuKcDiEiLLycGb7aeAdWfQoGWfZlYy5Kmdp5MqDhBwtCUqLlzJhfOnxxhPunmY3o76lV5%2DNkjZhMiZWYzub...">Find <b>Hello</b> From on eBay - Seriously, We have EVERYTHING</a>
  • 我也查过了,好像很奇怪!
  • @shamilpython 这是我朋友的编码网址。

标签: python html web-scraping beautifulsoup python-requests


【解决方案1】:

有多个类名为“result__a”的 DOM 元素。所以,不要指望你看到的第一个链接是你得到的第一个链接。

您提到的“乱码”是一个编码的 URL。您需要对其进行解码和解析以获取 URL 的参数(params)。

例如: "/l/?kh=-1&uddg=https%3A%2F%2Fwww.example.com"

上面的href包含两个参数,分别是kh和uddg。 我想 uddg 是您需要的实际链接。

以下代码将获取该特定类的所有 URL,未加引号。

import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs, unquote
html = requests.get('http://duckduckgo.com/html/?q=hello').content
soup = BeautifulSoup(html, 'html.parser')
for anchor in soup.find_all('a', attrs={'class':'result__a'}):
  link = anchor.get('href')
  url_obj = urlparse(link)
  parsed_url = parse_qs(url_obj.query).get('uddg', '')
  if parsed_url:
    print(unquote(parsed_url[0]))

【讨论】:

  • urllib.parse 的任何替代品?
  • @shamilpython urllib 使您的工作更轻松,并且是流行的库之一。如果你真的想要一个替代品,那就是'furl'
猜你喜欢
  • 2012-02-18
  • 1970-01-01
  • 2020-10-10
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 2021-08-17
  • 2017-05-29
  • 1970-01-01
相关资源
最近更新 更多