gpt4 book ai didi

python - BeautifulSoup findAll 在选择类时返回空列表

转载 作者:太空宇宙 更新时间:2023-11-04 11:21:52 25 4
gpt4 key购买 nike

指定类时 findall() 返回空列表

指定标签工作正常

import urllib2
from bs4 import BeautifulSoup

url = "https://www.reddit.com/r/Showerthoughts/top/?sort=top&t=week"

hdr = { 'User-Agent' : 'tempro' }
req = urllib2.Request(url, headers=hdr)
htmlpage = urllib2.urlopen(req).read()

BeautifulSoupFormat = BeautifulSoup(htmlpage,'lxml')
name_box = BeautifulSoupFormat.findAll("a",{'class':'title'})

for data in name_box:
print(data.text)

我试图只获取帖子的文本。当前代码不打印任何内容。如果我删除 {'class':'title'} 它会打印出帖子文本以及我不想要的帖子的用户名和评论。

我将 python2 与最新版本的 BeautifulSoup 和 urllib2 一起使用

最佳答案

要获得所有评论,您将需要一个像 selenium 这样的允许您滚动的方法。没有它,只是为了获得初步结果,您可以从 requests 响应中的脚本标记中获取

import requests
from bs4 import BeautifulSoup as bs
import re
import json

headers = {'User-Agent' : 'Mozilla/5.0'}
r = requests.get('https://www.reddit.com/r/Showerthoughts/top/?sort=top&t=week', headers = headers)
soup = bs(r.content, 'lxml')
script = soup.select_one('#data').text
p = re.compile(r'window.___r = (.*); window')
data = json.loads(p.findall(script)[0])
for item in data['posts']['models']:
print(data['posts']['models'][item]['title'])

关于python - BeautifulSoup findAll 在选择类时返回空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55808818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com