【问题标题】:Need a better way to find the tag to use in beautifulsoup需要一种更好的方法来查找要在 beautifulsoup 中使用的标签
【发布时间】:2021-04-27 15:54:21
【问题描述】:

这是我的代码,它将www.nytimes.com 的标题保存在 .txt 文件中。

使用 requests 和 beautifulsoup

import requests
from bs4 import BeautifulSoup

url = requests.get("https://www.nytimes.com/")
soup = BeautifulSoup(url.text, "html.parser")

with open(str(input("Please enter a file name: ")), "w") as f:
   for i in soup.find_all('p'):
      if i.a: 
         f.write(i.a.text.replace("\n", " ").strip())
      else: 
         f.write(i.contents[0].strip())

在代码中这一行:

for i in soup.find_all('p'):

假设找到所有标题不起作用。它只需要几个第一个标题而不是全部。

有没有更好的方法来写这行而不是去网站然后检查然后找到包含我需要的内容的标签。

【问题讨论】:

    标签: python python-3.x python-2.7 beautifulsoup


    【解决方案1】:

    我猜这是因为网页是动态的,这就是为什么你的“html.parser”没有给你所有的标题。尝试使用selenium模块抓取动态网页。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 2018-01-16
      • 2021-04-30
      • 2010-11-11
      相关资源
      最近更新 更多