【问题标题】:Accessing <li> element with no class id using Beautiful soup使用 Beautiful soup 访问没有类 ID 的 <li> 元素
【发布时间】:2016-09-05 21:30:48
【问题描述】:

我正在尝试在最终结果下的 ul 表中刮取 li 中的公司。源代码是这样的

import string
import re
import urllib2
import datetime
import bs4
from bs4 import BeautifulSoup

class AJSpider(object):

    def __init__(self):
        print ("initisizing")
        self.date = str(datetime.date.today())
        self.cur_url = "https://youinvest.moneyam.com/modules/forward-diary/?date={date}&period=month"
        self.datas = []
        print ("initisization done")


    def get_page(self,cur_date):
        url = self.cur_url
        try:
            my_page = urllib2.urlopen(url.format(date = cur_date)).read().decode("utf-8")
            my_soup = BeautifulSoup(my_page, "html.parser")

        except:
            print ('Failed')
        return my_soup

    def get_final(self, soup_page):
        temp_data = []
        final_result_section = soup_page.find("h3", text="Final Result")
        print final_result_section

    def start_spider(self):
        my_page = self.get_page(self.date)
        self.get_final(my_page)

def main():

    my_spider = AJSpider()
    my_spider.start_spider()

if __name__ == '__main__':
    main()

我在 stackoverflow 中发现了一个类似的问题 Beautiful Soup: Accessing <li> elements from <ul> with no id ,但是这里的这个确实有一个类 id,这让事情变得容易多了。

在我的场景中,请问如何从 ul 表中提取 li 元素?这里唯一的标识符实际上是h3标签的内容,即最终结果,但它不是id所以我不知道如何使用它。

【问题讨论】:

    标签: python html beautifulsoup html-parsing html-lists


    【解决方案1】:

    通过文本找到h3元素并得到following ul list

    ul = soup.find("h3", text="Final Result").find_next_sibling("ul")
    for li in ul.find_all("li"):
        print(li.span.get_text(), li.a.get_text())
    

    请注意,在最近的 BeautifulSoup 版本中,text 参数已重命名为 string,但由于向后兼容,它们都可以工作。

    【讨论】:

    • 为了提问者的利益,这里是这段代码的两行输出,用于问题中的 HTML 片段: 01 Sep 16 Hays PLC [HAS] 01 Sep 16 Alumasc集团 PLC [ALU]
    • 非常感谢。我试过了,但是我得到了 TypeError: find() 没有关键字参数,我尝试了 text 和 string,请问这个错误是如何引发的?
    • @Victor 看起来你正在使用BeautifulSoup 3 - 如果你有以下导入:from BeautifulSoup import BeautifulSoup,你应该升级!通过:pip install beautifulsoup4 安装 Beautifulsoup 4,并将导入更改为 from bs4 import Beautifulsoup
    • 我确实使用 bs4 import bs4 from bs4 import BeautifulSoup
    • @Victor 好的,请编辑问题并发布您的完整代码。
    猜你喜欢
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2020-04-06
    • 1970-01-01
    • 2018-03-15
    相关资源
    最近更新 更多