【问题标题】:Python web-scraping outputPython网络抓取输出
【发布时间】:2020-08-27 02:41:33
【问题描述】:

我想制作一个脚本,将 bing 搜索结果的链接打印到控制台。问题是当我运行脚本时没有输出。我相信网站认为我是机器人?

from bs4 import BeautifulSoup
import requests

search = input("search for:")
params = {"q": "search"}
r = requests.get("http://www.bing.com/search", params=params)

soup = BeautifulSoup(r.text, "html.parser")
results = soup.find("ol", {"id": "b_results"})
links = results.find_all("Li", {"class": "b_algo"})

for item in links:
    item_text = item.find("a").text
    item_href = item.find("a").attrs["href"]

    if item_text and item_href:
        print(item_text)
        print(item_href)

【问题讨论】:

  • find_all 可以区分大小写吗?即Lili

标签: html python-3.x web-scraping beautifulsoup


【解决方案1】:

您需要使用搜索变量而不是“搜索”。您的脚本中还有一个错字:li 是小写。

更改这些行:

params = {"q": "search"}
.......
links = results.find_all("Li", {"class": "b_algo"})

到这里:

params = {"q": search}
........
links = results.find_all("li", {"class": "b_algo"})

请注意,有些查询不会返回任何内容。 “填字游戏”有结果,但“花生”没有。结果页面结构可能因查询而异。

【讨论】:

    【解决方案2】:

    这段代码有2个问题-

    1. Search 是一个变量名,因此不应与引号一起使用。改成下面

    params = {"q": search}

    1. 当您在获取链接时将变量名包含在引号内时,它将成为静态链接。对于动态链接,您应该按照以下方式进行 -

    r = requests.get("http://www.bing.com/"+search, params=params)

    进行这 2 项更改后,如果仍然没有得到任何输出,请检查结果变量中是否使用了正确的标记。

    【讨论】:

      猜你喜欢
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多