Beautiful Soup 4 返回 “[]”,我该如何解决这个错误?

huangapple go评论63阅读模式
英文:

Bs4 is returning "[]" how do I go about fixing this error?

问题

我正在尝试创建一个代码,用于识别用户输入的搜索结果是否返回空白页面,我通过识别屏幕上是否存在特定文本来实现这一目标。

import requests
from bs4 import BeautifulSoup

site = input("输入顶级域名的域名:")
textsearch = input("输入您要查找的文本:")

r = requests.get(f"https://www.google.com/search?q=site%3A.{site}+%22{textsearch}%22")

soup = BeautifulSoup(r.text, 'html.parser')
search = soup.find_all(text="Try different keywords")
print(search)

问题是,当我知道该网页返回零结果时,这段代码会返回"[]",我该如何修复这个问题?

英文:

I am trying to make a code that identifies if they search the use has inputted returns a blank page or not and I am doing this by identifying if there is certain text on the screen

import requests
from bs4 import BeautifulSoup

site = input("Input the domain of the top level domain: ")
textsearch = input("Input what text you're looking for: ")

r = requests.get(f"https://www.google.com/search?q=site%3A.{site}+%22{textsearch}%22")

soup = BeautifulSoup(r.text, 'html.parser')
search = soup.find_all(text="Try different keywords")
print(search)

The problem is this code is returning "[]" when I know this web page returns zero results, how do I go about fixing this?

答案1

得分: 0

只要您需要检查该短语是否出现在任何位置,那么您不需要Beautiful Soup 4(bs4)。

只需执行if "尝试不同的关键词" in r.text: print("错误:无结果")

英文:

if all you need to do is see if that phrase is present anywhere then you do not need bs4

just do if "Try different keywords" in r.text: print("ERROR no results")

huangapple
  • 本文由 发表于 2023年4月4日 09:49:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定