【问题标题】:Beautiful soup returns empty array美汤返回空数组
【发布时间】:2021-02-21 12:43:19
【问题描述】:

我正在使用漂亮的汤从谷歌搜索中找到第一个命中。

寻找“堆栈溢出”它应该找到https://www.stackoverflow.com

代码主要取自here 但是,它突然停止工作,结果[0] 被索引超出范围。 print results[0] IndexError: list index out of range

我怀疑这是一个缓存问题,因为它工作正常,然后在没有更改代码的情况下停止了。我也重新启动并清除了缓存,但仍然没有结果。

#!/usr/bin/python
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
import requests
import webbrowser # for webrowser, duh!
import re


#------------------------------------------------
def write_it(s, f):
  # w for over write
  file = open(f, "w")
  file.write(s)
  file.close()

#------------------------------------------------
def URL_encode_space(s):
  return re.sub(r"\s", "%20", s)
#------------------------------------------------
def URL_decode_space(s):
  return re.sub(r"%20", " ", s)
#------------------------------------------------


urlBase = "https://google.com"
searchRequest = "Stack Overflow"

print searchRequest
searchRequest = URL_encode_space(searchRequest)

# String literal for HTML quote
q = "%22" # is a "


numOfResults = 10

myURL = urlBase + "/search?q=" + q + searchRequest + q + "&num={" + str(numOfResults) + "}"

page = requests.get(myURL)
soup = BeautifulSoup(page.text, "html.parser")
links = soup.findAll("a")
results = []

for link in links:

  link_href = link.get('href')
  if "url?q=" in link_href and not "webcache" in link_href:
    print (link.get('href').split("?q=")[1].split("&sa=U")[0])
    results.append(link.get('href').split("?q=")[1].split("&sa=U")[0])

  print results[0]

# open web browser?
webbrowser.open(myURL)

我显然可以检查“len(results)”来消除错误,但这并不能解释为什么它不再起作用。

【问题讨论】:

  • 网址更改。适用于某些网址的代码不适用于其他网址。这里发生的确切情况尚不清楚,但从特定形式的 url 中提取信息的尝试在某些时候停止工作也就不足为奇了。
  • 如果你在循环中执行print(link_href)break,你会看到第一个url 不满足if 标准,当你执行results[0] 时,你会得到错误。可能您需要在 if 块内缩进 print(results[0]) 块。
  • 如果你正在解析的页面不断变化,可能是第一次迭代if条件不满足,结果为空。您可以尝试在循环外打印结果
  • 我怀疑代码停止工作,因为谷歌认为它“来自您的计算机网络的异常流量”

标签: python beautifulsoup


【解决方案1】:

就像上面的人说的那样,不清楚是什么导致了问题。

确保您使用的是user agent

我从我的其他 answer 中获取此代码(从谷歌搜索结果中抓取标题、摘要和链接)。

代码和完整example

from bs4 import BeautifulSoup
import requests
import json

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=java&oq=java',
                    headers=headers).text

soup = BeautifulSoup(html, 'lxml')

summary = []

for container in soup.findAll('div', class_='tF2Cxc'):
    heading = container.find('h3', class_='LC20lb DKV0Md').text
    article_summary = container.find('span', class_='aCOpRe').text
    link = container.find('a')['href']

    summary.append({
        'Heading': heading,
        'Article Summary': article_summary,
        'Link': link,
    })

print(json.dumps(summary, indent=2, ensure_ascii=False))

或者,您可以使用来自 SerpApi 的 Google Organic Results API 来获得这些结果。 这是一个免费试用的付费 API。

部分 JSON:

{
  "position": 1,
  "title": "Java | Oracle",
  "link": "https://www.java.com/",
  "displayed_link": "https://www.java.com",
  "snippet": "Java Download. » What is Java? » Need Help? » Uninstall. About Java. Go Java Java Training Java + Greenfoot Oracle Code One Oracle Academy for ..."
}

要集成的代码:

import os
from serpapi import GoogleSearch

params = {
    "engine": "google",
    "q": "stackoverflow",
    "api_key": os.getenv("API_KEY"),
}

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

for result in results["organic_results"]:
   print(f"Link: {result['link']}")

输出:

Link: https://stackoverflow.com/
Link: https://en.wikipedia.org/wiki/Stack_Overflow
Link: https://stackoverflow.blog/
Link: https://stackoverflow.blog/podcast/
Link: https://www.linkedin.com/company/stack-overflow
Link: https://www.crunchbase.com/organization/stack-overflow

免责声明,我为 SerpApi 工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多