【问题标题】:Python and Selenium - Scrape data from multiple siblingsPython 和 Selenium - 从多个同级中抓取数据
【发布时间】:2014-04-08 23:33:04
【问题描述】:

好的,我是 python 的新手,当然还有 Selenium。我正在尝试抓取数据页面,然后在 python 中使用该数据并使用 selenium 点击链接和存储时间等...

我遇到的问题是页面的格式不是我想要的。而不是拥有这个... 标题 链接1 链接2 标题2 链接3 链接4/a> 我有这个

<tr>
    <td>title<td>
</tr>
<tr>
    <td>
        <a href>link1</a>
    </td>
</tr>
<tr>
    <td>
        <a href>link2</a>
    </td>
</tr>
<tr>
    <td>
        <a href>link3</a>
    </td>
</tr>

这是我正在使用的 HTML - http://pastebin.com/663T7mXc

我想要做的是,获取所有链接,但根据它们所属的标题对它们进行分类。例如。 标题 链接 1 链接 2 标题 2 链接 3 链接 4 链接 5 标题 3 链接 6

等等。

由于链接不是与标题相同标签的子标签,我发现这对我来说几乎是不可能的。

这是我目前所拥有的

def test():
    print ("testing")
    browser = webdriver.Chrome()
    browser.get("http://urlforpage.com")
    meetings = browser.find_elements_by_xpath('/html/body/div[2]/table[2]/tbody/tr/td')
    i=0
    for meet in meetings:
        venue = meet.get_attribute("class")
        if venue == "bold":
            print "Venue: " + str(i) + " " + meet.text
            i+=1
        elif venue == "racing-insert-linked-events nextoff-inner-wrapper nextoff-scrollable-wrapper":
            print ("links")
            print venue.href


test()

我根据类的“粗体”类来拉出标题,我的问题是,我不知道如何拉取其他标签内链接的 url 和链接文本。

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: python html selenium web-scraping


    【解决方案1】:

    尝试尽可能少地更改您的代码,这是您所追求的吗?

    def test():
        print ('testing')
        browser = webdriver.Chrome()
        browser.get('http://urlforpage.com')
        meetings = browser.find_elements_by_xpath('/html/body/div[2]/table[2]/tbody/tr/td')
        for meet in meetings:
            if meet.get_attribute('class') == 'bold':
                print 'Venue: {venue}'.format(venue=meet.text)
            else:
                try:
                    anchor = meet.find_element_by_tag_name('a')
                    print 'link: {link}, text: {text}'.format(link = anchor.get_attribute('href'), text = anchor.text)
                except NoSuchElementException:
                    pass  # Are you worried if something is neither a title (bold) nor contains an anchor?
    
    
    test()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多