【问题标题】:HTML Specific <h1> Text in PythonPython 中的 HTML 特定 <h1> 文本
【发布时间】:2020-10-01 02:18:56
【问题描述】:

我只想在 python 中获取 page &lt;h1&gt;This is Title&lt;/h1&gt; 的标题。

我尝试了一些方法,但没有得到想要的结果。

import requests

from bs4 import BeautifulSoup


response = requests.get("https://www.strawpoll.me/20321563/r")

html_content = response.content

soup = BeautifulSoup(html_content, "html.parser")

for i in soup.get_text("p", {"class": "result-list"}):
    print(i)

【问题讨论】:

    标签: html python-3.x html-parsing


    【解决方案1】:

    将 lxml 用于此类任务。你也可以用beautifulsoup。

    import lxml.html
    t = lxml.html.parse(url)
    print t.find(".//title").text
    

    (来自 How can I retrieve the page title of a webpage using Python?,作者 Peter Hoffmann)

    【讨论】:

      【解决方案2】:

      我将给定的代码添加到我的。

      title = soup.title
      print(title.string[:-24:])  # Last 24 character of title is always constant.
      

      【讨论】:

        【解决方案3】:

        如果还是得不到想要的结果,试试这个方法。

        import urllib
        import bs4
        from urllib.request import urlopen as uReq
        from bs4 import BeautifulSoup as soup
        
        my_url = 'https://www.strawpoll.me/20321563/r'
        uCLient = uReq(my_url)
        page_html = uCLient.read()
        uCLient.close()    
        page_soup = soup(page_html,"html.parser")
        _div = page_soup.find(lambda tag: tag.name=='div' and tag.has_attr('id') and 
        tag['id']=="result-list") 
        title = _div.findAll(lambda tag: tag.name=='h1')
        
        print(title)
        

        输出:[&lt;h1&gt;This is Title&lt;/h1&gt;]

        【讨论】:

        • 其实我只需要“This is Title”
        【解决方案4】:

        你可以使用 BeautifulSoup 看:

        from bs4 import BeautifulSoup
        
        data = "html as text(Source)"
        
        soup = BeautifulSoup(data)
        
        p = soup.find('h1', attrs={'class': 'titleClass'})
        p.a.extract()
        print p.text.strip()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-10-19
          • 1970-01-01
          • 1970-01-01
          • 2022-10-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-24
          相关资源
          最近更新 更多