使用BS4错误从DIV获取所有标题标签



我正在尝试使用BS4中的所有项目获取标题标签,然后打印出所有标题。如果我做 print(soup.find(" a",attrs = {" class":" detlink"}([" title"]((我只获得了其中一个标题。如果我切换"选择"以查找或find_all,我会收到一个错误msg说:

 print(soup.findAll("a", attrs={"class": "detLink"})["title"])
 TypeError: list indices must be integers or slices, not str

这是我的代码:

def test():
    url_to_scrape = "https://test.com"
    r = requests.get(url_to_scrape)
    soup = BeautifulSoup(r.text, "html5lib")
    print(soup.select("a", attrs={"class": "detLink"})["title"])
test()

如何获得所有项目的标题?

请尝试:

def test():
    url_to_scrape = "https://test.com"
    r = requests.get(url_to_scrape)
    soup = BeautifulSoup(r.text, "html5lib")
    titles = [div["title"] 
              for div in soup.find_all("a", attrs={"class": "detLink"})]
    print(titles)
test()

有效地使用标题的列表理解。

最新更新