Skip to main content
 首页 » 编程设计

python之BeautifulSoup 和解析 reddit

2024年10月17日8grandyang

刚刚尝试解析提交的 reddit shower 想法,但遇到了一个问题:

 path = 'https://www.reddit.com/r/Showerthoughts/' 
 
 with requests.Session() as s: 
 
    r = s.get(path) 
    soup = BeautifulSoup(r.content, "lxml") 
 
    # print(soup.prettify()) 
 
    threads = soup.find_all('p') 
 
 
    for thread in threads: 
        soup = thread 
        text = soup('a') 
        try: 
            print(text[0]) 
        except: 
            pass 

在这段代码中,我试图获取每个提交的标题,该标题包含在 < p > 标记中,然后是带有类“title may-blank”的 < a > 标记。但是上面的代码返回所有带有 a 标签的元素,其中有很多,甚至认为标题在那里我将不得不再经历两次 soup.findAll() 的交互,我确信那里是一种搜索汤以打印所有标题的手动方式较少

据我所知,我尝试这样做

titles = soup.findAll( "a", {"class":"title may-blank}) 对于标题中的标题: 打印(标题.字符串)
但这没有用 有什么想法吗? PS 我知道这可以通过 reddit API 完成并且效率更高,但我想提高我的解析技能,因为它们还没有达到标准。谢谢你的帮助

请您参考如下方法:

它们是 css 类,您还需要添加一个用户代理:

import requests 
from bs4 import BeautifulSoup 
path = 'https://www.reddit.com/r/Showerthoughts/' 
headers ={"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36"} 
with requests.Session() as s: 
    r = s.get(path, headers=headers) 
    soup = BeautifulSoup(r.content, "lxml") 
    threads = soup.select('a.title.may-blank') 
    for a in threads: 
        print(a) 

您也可以使用 soup.find_all("a", class_="title") 但这可能比您想要的匹配更多。