【问题标题】:How to identify the correct class for Beautifulsoup?如何识别 Beautifulsoup 的正确类?
【发布时间】:2022-01-17 11:30:20
【问题描述】:

我正在尝试学习报废,我面临的一个问题是识别正确的类名,是否有任何特定的规则/方法可以遵循来识别正确的类名例如在下面的代码中,我正在尝试从 stackoverflow 获取问题列表页面,为此我在第一个问题上单击检查 & 我可以看到类名为 question-hyperlink 但是当我尝试下面的代码时,我得到空结果,同样如果我尝试使用 divname 摘要我得到相同的空结果请指导我如何解决这个问题并避免在未来的情况下

import requests
from bs4 import BeautifulSoup
 
website = 'https://stackoverflow.com/'
r = requests.get(website)

if r.status_code == 200:
    print(f"Connected to {website}")
    soup = BeautifulSoup(r.content, 'html.parser')
    s = soup.find_all(class_name='question-hyperlink')
    print(s)
else:
    print(r)
    
print("Done")

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    您使用的网址没有任何问题 - https://stackoverflow.com 仅显示一个起始页面,除非您已登录。

    您需要将网址更改为https://stackoverflow.com/questions

    另外,您应该在find_all() 中使用class_=,而不是class_name=

    然后它就可以正常工作了。

    import requests
    from bs4 import BeautifulSoup
    
    website = 'https://stackoverflow.com/questions/'
    
    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:95.0) Gecko/20100101 Firefox/95.0",
    }
    r = requests.get(website, headers=headers)
    
    if r.status_code == 200:
        print(f"Connected to {website}")
        soup = BeautifulSoup(r.text, 'html.parser').find_all("a", class_="question-hyperlink")
        print(len(soup))
    

    输出:

    20
    

    【讨论】:

      【解决方案2】:

      您专注于类名称“问题超链接”。在漂亮的汤里,你可以简单地写一些像soup.find_all('div', class_='summary') 获取特定的课程。

      import requests
      from bs4 import BeautifulSoup
       
      
      url = 'https://stackoverflow.com/questions/tagged/python'
      
      
      #A function that gets the H3 titles for the python tagged stackoverflow
      #It saves and outputs a list with all the titles
      
      
      def main():
          #get all elements from the entire page
          r = requests.get(url)
          soup = BeautifulSoup(r.text, 'html.parser')
          questions = soup.find_all('div', class_='summary')
          
          #only get me the H3 html tags
          question_text = []
          for question in questions:
              question_text.append(question.find('h3').text)
          print(question_text)
      
      
      if __name__ == '__main__':
          main()
      

      Output: ['How do I verify if certificate is ca trusted in python?',...]
      

      【讨论】:

        猜你喜欢
        • 2013-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-02
        • 2011-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多