【问题标题】:How to scrape a content from links stored in a list using beautiful soup?如何使用漂亮的汤从存储在列表中的链接中抓取内容?
【发布时间】:2018-07-22 12:04:46
【问题描述】:

我想抓取主网站上所有帖子的标题。 main 是一个包含 6 或 7 个 url 的列表:

import requests 
from bs4 import Beautifulsoup 

r=requests.get("https://forums.oneplus.com/")
s=BeautifulSoup(r.content)
links=s.find_all("a",{"class" : "focus-content"})
url2=[] 
for link in links:
    url2.append(link.get("href"))

url1="https://forums.oneplus.com/"
for u in url2:
    main=url1+u
    print(main)

for m in main:
    r1=requests.get(m)
    s1=BeautifulSoup(r1)
    title=s1.find("span", {"class" : "title"})
    print(title)

【问题讨论】:

  • 您不能将请求对象传递给美丽的汤。你应该这样做:r1=requests.get(m).text。 BS4 也可能会给你一个警告:BeautifulSoup(r1, 'html.parser')。然后打印 title 不会给你你想要的东西,title.text 会(因为 title 是一个汤元素对象,而不是一个字符串)。您没有正确返回标题,我建议将它们附加到列表中。
  • 你没有告诉我们你的代码有什么问题。它会给出错误吗?它根本没有做任何事情吗?

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

您需要将变量main 声明为列表。在您的代码中,您在循环的每次迭代中更新变量main。最后,main 将是包含来自url2 列表的最后一个 url 的字符串。如果您随后将 main 提供给下一个循环,它将遍历单个字符。

经过一些外观上的改变,这应该会得到你的标题:

import requests
from bs4 import BeautifulSoup

r=requests.get("https://forums.oneplus.com/")
s=BeautifulSoup(r.content, 'lxml')
links=s.find_all("a",{"class" : "focus-content"})
url2=[]
for link in links:
    url2.append(link.get("href"))

url1 = "https://forums.oneplus.com/"
main = []
for u in url2:
    main.append(url1 + u)

for m in main:
    r1 = requests.get(m)
    s1 = BeautifulSoup(r1.text, 'lxml')
    title=s1.find("span", {"class" : "title"})
    print(title.text.strip())

打印:

Weekly 240: We release the updates and get reading
Shot on OnePlus: Part 6 – Best Slo-mo Video / Animal Photos
Android P Beta Developer Preview 3 for OnePlus 6
[Let's Talk] To whom are you gonna give your appreciation in this Community?
[Let's Talk] What Does Your OnePlus Device Replace?
[Let's Talk]  Loyalty to tech companies

【讨论】:

  • 嗨 Andrej,感谢您的回复,但在尝试您的代码后,我仍然遇到相同的错误。下面的代码用于从 bs4 import Beautifulsoup r=requests.get 获取主列表导入请求的值("forums.oneplus.com/") s=BeautifulSoup(r.content) links=s.find_all("a",{"class" : "focus-content"}) url2=[] 链接中的链接:url2.append(link .get("href")) url1="forums.oneplus.com" for u in url2: main=url1+u 请告诉我哪里出错了
  • @sonu 你能编辑你的问题并在那里发布错误吗?否则很难看出有什么问题......
  • 嗨 Andrej 我无法编辑我的问题以附加错误最后一行错误是 MissingSchema: Invalid URL 'h': No schema provided.也许你的意思是 http://h?这是第一行 MissingSchema: Invalid URL 'h': No schema provided。也许你的意思是 http://h?
  • 不知道我何时尝试编辑它显示缩进错误或添加更多我所做的 cmets
  • 嗨 andrej 我已将我的代码和错误放在此链接anotepad.com/notes/hn7k2k
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 2020-09-15
  • 2019-05-23
  • 2020-08-14
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 2017-10-05
相关资源
最近更新 更多