【问题标题】:Beautiful Soup returning only the last URL of a txt fileBeautiful Soup 仅返回 txt 文件的最后一个 URL
【发布时间】:2020-10-27 21:00:11
【问题描述】:

我正在尝试解析 txt 文件的一组 url,但 Beautiful Soup 只返回最后一个 url 的内容。这是一组来自 LetterBoxD 网站的电影评论网址。例如,如果文件有 10 个 url,前 9 个我得到“无”。只有第 10 个正确返回。有人可以帮我吗?

from bs4 import BeautifulSoup
import requests

with open('list_of_urls.txt', 'r') as f:
  x = f.readlines()

for url in x:
  page = requests.get(url)
  soup = BeautifulSoup(page.content, 'html.parser')
  text = soup.find(class_='review body-text -prose -hero -loose')
  print(text)

【问题讨论】:

  • 可能你指定的类只存在于最后一个url的页面源中?
  • 介意分享这 10 个网址的样本吗?

标签: web-scraping beautifulsoup python-requests


【解决方案1】:

要按多个类查找元素,应使用类名数组:

text = soup.find(class_= ['review', 'body-text', '-prose', '-hero', '-loose'])

看起来,letterboxd.com 可能在评论元素上有不同的类组合,例如review body-text -prose -hero prettify,所以我建议少课后搜索,例如

text = soup.find(class_= ['review', 'body-text'])

【讨论】:

    【解决方案2】:

    非常感谢!但我发现 URL 末尾有一个 \n 。所以我使用 rstrip('\n') 删除它。

    顺便说一句,亚历山德拉的提示对未来的提取有很大帮助!谢谢!

    这是我的新代码:

    for url in x:
      url = url.rstrip('\n')
      page = requests.get(url)
      soup = BeautifulSoup(page.content, 'html.parser')
      text = soup.find(class_='review body-text -prose -hero -loose')
      print(text)
    

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多