【问题标题】:Python Extracting First Link in Google SearchPython 提取 Google 搜索中的第一个链接
【发布时间】:2020-09-20 14:22:41
【问题描述】:

我正在尝试向 Google 发送搜索查询,并仅提取找到的第一个结果。我只需要网址。这是迄今为止我尝试过的示例,但由于某种原因,我无法获取 href 值。

import requests
from bs4 import BeautifulSoup
import xlwt
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from urllib.parse import urlparse

name = "Joe Sample"
search_query = 'string of info ' + name + ' more info'


driver = webdriver.Firefox(executable_path="geckodriver")
driver.get("https://www.google.com")
driver.find_element_by_name('q').send_keys(search_query)
time.sleep(2)
driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[3]/center/input[1]').send_keys(Keys.ENTER)



results = driver.find_elements_by_xpath('/html/body/div[7]/div[2]/div[10]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div[1]/div/div[2]/span/div/ol/li/a')
    href = results.get_attribute('href')
    print(urlparse.parse_qs(urlparse(href).query)['q'])

代码的前半部分工作正常,问题是找到第一个链接——并且只抓取 URL。

【问题讨论】:

    标签: python selenium-webdriver web-scraping urllib


    【解决方案1】:

    我假设应该是href = results[0].get_attribute(“href”)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-14
      • 2019-12-15
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2021-10-28
      • 1970-01-01
      • 2016-06-06
      相关资源
      最近更新 更多