【问题标题】:Google search gives redirect url, not real url python谷歌搜索给出重定向 url,而不是真正的 url python
【发布时间】:2018-05-17 00:56:40
【问题描述】:

所以基本上我的意思是,当我搜索 https://www.google.com/search?q=turtles 时,第一个结果的 href attribute 是 google.com/url 重定向。现在,如果我只是用浏览器浏览互联网,我不会介意这一点,但我正在尝试在 python 中获取搜索结果。所以对于这段代码:

import requests
from bs4 import BeautifulSoup

def get_web_search(query):
    query = query.replace(' ', '+') # Replace with %20 also works
    response = requests.get('https://www.google.com/search', params={"q": 
    query})
    r_data = response.content
    soup = BeautifulSoup(r_data, 'html.parser')
    result_raw = []
    results = []
    for result in soup.find_all('h3', class_='r', limit=1):
        result_raw.append(result) 

    for result in result_raw:
        results.append({
            'url' : result.find('a').get('href'),
            'text' : result.find('a').get_text()
        })

    print(results)

get_web_search("turtles")

我希望

[{ 网址:“https://en.wikipedia.org/wiki/Turtle”, 文本:“乌龟 - 维基百科” }]

但我得到的是

[{'url': '/url?q=https://en.wikipedia.org/wiki/Turtle&sa=U&ved=0ahUKEwja-oaO7u3XAhVMqo8KHYWWCp4QFggVMAA&usg=AOvVaw31hklS09NmMyvgktL1lrTN', 'text': '乌龟-维基百科'}

我在这里缺少什么吗?我是否需要提供不同的标头或其他请求参数?任何帮助表示赞赏。谢谢。

注意:我看过其他关于此的帖子,但我是初学者,所以我无法理解那些,因为它们不在 python 中

【问题讨论】:

  • 你可以删除 /url?q= 部分
  • 实际上在重定向 url 中还有其他内容。像sa= 部分和一堆其他东西。它似乎因请求而异。所以这不会总是工作

标签: python web-scraping beautifulsoup google-search


【解决方案1】:

您可以使用CSS 选择器来获取这些链接。

soup.select_one('.yuRUbf a')['href']

代码和example in the online IDE

from bs4 import BeautifulSoup
import requests

headers = {
    'User-agent':
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
    "Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}

html = requests.get('https://www.google.com/search?q=turtles', headers=headers)
soup = BeautifulSoup(html.text, 'html.parser')
# iterates over organic results container
for result in soup.select('.tF2Cxc'):
    # extracts url from "result" container 
    url = result.select_one('.yuRUbf a')['href']
    print(url)

------------
'''
https://en.wikipedia.org/wiki/Turtle
https://www.worldwildlife.org/species/sea-turtle
https://www.britannica.com/animal/turtle-reptile
https://www.britannica.com/story/whats-the-difference-between-a-turtle-and-a-tortoise
https://www.fisheries.noaa.gov/sea-turtles
https://www.fisheries.noaa.gov/species/green-turtle
https://turtlesurvival.org/
https://www.outdooralabama.com/reptiles/turtles
https://www.rewild.org/lost-species/lost-turtles
'''

或者,您可以使用来自 SerpApi 的 Google Search Engine Results API 执行相同的操作。

这是一个付费 API,可免费试用 5,000 次搜索,主要区别在于您所要做的就是浏览结构化的 JSON,而不是找出为什么不起作用。

要集成的代码:

from serpapi import GoogleSearch

params = {
  "api_key": "YOUR_API_KEY",
  "engine": "google",
  "q": "turtle",
}

search = GoogleSearch(params)
results = search.get_dict()

for result in results['organic_results']:
    print(result['link'])

--------------
'''
https://en.wikipedia.org/wiki/Turtle
https://www.britannica.com/animal/turtle-reptile
https://www.britannica.com/story/whats-the-difference-between-a-turtle-and-a-tortoise
https://turtlesurvival.org/
https://www.worldwildlife.org/species/sea-turtle
https://www.conserveturtles.org/
'''

免责声明,我为 SerpApi 工作。

【讨论】:

    【解决方案2】:

    您可以将 selenium 与 python 和 BeautifulSoup 结合使用。无论网页是启用 javascript 还是普通网页,它都会为您提供第一个结果:

    from selenium import webdriver
    from bs4 import BeautifulSoup
    
    def get_data(search_input):
        search_input = search_input.replace(" ","+")
        driver.get("https://www.google.com/search?q=" + search_input)
        soup = BeautifulSoup(driver.page_source,'lxml')
        for result in soup.select('h3.r'):
            item = result.select("a")[0].text
            link = result.select("a")[0]['href']
            print("item_text: {}\nitem_link: {}".format(item,link))
            break
    
    if __name__ == '__main__':
        driver = webdriver.Chrome()
        try:
            get_data("turtles")
        finally:
            driver.quit()
    

    输出:

    item_text: Turtle - Wikipedia
    item_link: https://en.wikipedia.org/wiki/Turtle
    

    【讨论】:

      【解决方案3】:

      只需按照链接的重定向,它就会转到正确的页面。假设您的链接在 url 变量中。

      import urllib2
      url = "/url?q=https://en.wikipedia.org/wiki/Turtle&sa=U&ved=0ahUKEwja-oaO7u3XAhVMqo8KHYWWCp4QFggVMAA&usg=AOvVaw31hklS09NmMyvgktL1lrTN"
      url = "www.google.com"+url
      response = urllib2.urlopen(url) # 'www.google.com/url?q=https://en.wikipedia.org/wiki/Turtle&sa=U&ved=0ahUKEwja-oaO7u3XAhVMqo8KHYWWCp4QFggVMAA&usg=AOvVaw31hklS09NmMyvgktL1lrTN'
      response.geturl() # 'https://en.wikipedia.org/wiki/Turtle'
      

      这很有效,因为您将 google 重定向到您每次搜索时真正点击的 url。这段代码,基本上只是跟随重定向,直到它到达真正的 url。

      【讨论】:

      • 谢谢。而且,为什么还会存在这种重定向?
      • @KidDoesCodingAndHasNoFriends 我不太确定,可能是因为他们可以跟踪您点击的链接。如果它解决了您的问题,请接受它作为答案:)(要接受它,请单击绿色复选标记)
      • 完成!抱歉,我是这个网站的菜鸟,所以我不知道 :'(
      • @KidDoesCodingAndHasNoFriends 没问题!
      【解决方案4】:

      使用这个提供谷歌搜索的包

      https://pypi.python.org/pypi/google

      【讨论】:

      • 首先,感谢您的回答。但我想自己编写代码,而不是使用更多库,因为这是我的一个项目:P
      猜你喜欢
      • 1970-01-01
      • 2013-04-07
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多