【问题标题】:Web Scraping: How to get the classWeb Scraping:如何获取课程
【发布时间】:2020-10-20 09:47:15
【问题描述】:

我想在运行程序时获取班级的信息输出为“无”

import requests
import bs4
import lxml

res =requests.get('https://www.reddit.com/r/Python/')

soup = bs4.BeautifulSoup(res.text,'lxml')
link = 'https://www.reddit.com/r/Python/'

div = soup.find('div', {"_1lwNBHmCQJObvqs1fXKSYR" : link}) #This is the class of the New title kinda thing
text = div
print(text)

我得到的输出是

None

我该怎么办? 感谢您的帮助!

【问题讨论】:

    标签: python html web web-scraping beautifulsoup


    【解决方案1】:

    您必须传递一个dictionarykey 是属性名称,value 是属性值。这就是你的做法:

    div = soup.find('div', {"class":"_1lwNBHmCQJObvqs1fXKSYR"}) #Finds the div with class "_1lwNBHmCQJObvqs1fXKSYR"
    text = div.text #Identifies text of the div tag
    print(text)
    

    输出:

    hot
    

    除了传递dictionary,您还可以将它们作为单独的参数传递,如下所示:

    div = soup.find('div', class_ = "_1lwNBHmCQJObvqs1fXKSYR") #An "_" is used after class because class is a keyword in python
    text = div.text #Identifies text of the div tag
    print(text)
    

    输出:

    hot
    

    如果要查找具有相同类的所有元素的文本,请使用find_all 方法。这就是你的做法:

    divs = soup.find_all('div', {'class':"_1lwNBHmCQJObvqs1fXKSYR"})
    
    for div in divs:
        print(div.text)
    

    输出:

    hot
    new
    top
    

    【讨论】:

    • 当我尝试运行 div = soup.find('div', class_ = "_1lwNBHmCQJObvqs1fXKSYR") #An "_" is used after class because class is a keyword in python text = div.text #Identifies text of the div tag print(text) 它给了我一个错误说 line 10, in <module> text = div.text#Identifies text of the div tag AttributeError: 'NoneType' object has no attribute 'text'
    • 是这样吗?它对我来说没问题。如果您发布完整的代码会更好。
    • import requests import bs4 import lxml res =requests.get('https://roobet.com/crash') soup = bs4.BeautifulSoup(res.text,'lxml') div = soup.find('div', class_ = "_1lwNBHmCQJObvqs1fXKSYR") #An "_" is used after class because class is a keyword in python text = div.text#Identifies text of the div tag print(text)
    • 我提供的代码仅适用于reddit。不同网站中的元素有不同的类。所有人都没有相同的班级。只需找到要抓取的元素的类并将该类提供给 class_ 参数即可。然后就可以了。
    • 感谢您的帮助。我的错,我在这里有点新 我该怎么做? (最佳答案)
    猜你喜欢
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2021-11-17
    相关资源
    最近更新 更多