代码之家  ›  专栏  ›  技术社区  ›  Harrison

打印特定行(Beautifulsoup)

  •  0
  • Harrison  · 技术社区  · 10 年前

    目前,我的代码正在通过链接解析并打印网站上的所有信息。我只想打印 网站上的一个特定行 .我该怎么做呢?

    这是我的代码:

    from bs4 import BeautifulSoup
    import urllib.request
    
    r = urllib.request.urlopen("Link goes here").read()
    soup = BeautifulSoup(r, "html.parser")
    
    # This is what I want to change. I currently have it printing everything.
    # I just want a specific line from the website
    
    print (soup.prettify())
    
    2 回复  |  直到 10 年前
        1
  •  4
  •   kulan    10 年前
    li = soup.prettify().split('\n')
    print str(li[line_number-1])
    
        2
  •  3
  •   Community Mohan Dere    9 年前

    不要使用漂亮的打印来尝试和解析tds,具体选择标记,如果属性是唯一的,则使用它;如果类名是唯一的则使用它:

    td = soup.select_one("td.content")
    td = soup.select_one("td[colspan=3]")
    

    如果是第四个td:

    td = soup.select_one("td:nth-of-type(4)")
    

    如果它在特定的表中,那么选择该表,然后在表中找到td,尝试将html拆分为行,索引实际上比使用 regex to parse html .

    您可以使用td前面的粗体标记中的文本来获取特定td,即 财政部建筑分类: :

    In [19]: from bs4 import BeautifulSoup
    
    In [20]: import urllib.request
    
    In [21]: url = "http://a810-bisweb.nyc.gov/bisweb/PropertyProfileOverviewServlet?boro=1&houseno=1&street=park+ave&go2=+GO+&requestid=0"
    
    In [22]: r = urllib.request.urlopen(url).read()
    
    In [23]: soup = BeautifulSoup(r, "html.parser")
    
    In [24]: print(soup.find("b",text="Department of Finance Building Classification:").find_next("td").text)
    O6-OFFICE BUILDINGS
    

    选择第n个表和行:

    In [25]: print(soup.select_one("table:nth-of-type(8) tr:nth-of-type(5) td[colspan=3]").text)
    O6-OFFICE BUILDINGS