【问题标题】:Can only get first row in table when scraping with Selenium in python在 python 中使用 Selenium 抓取时只能获取表中的第一行
【发布时间】:2017-01-30 17:28:45
【问题描述】:

我正在尝试从BGG 中抓取排名数据。

HTML的基本结构如下:

<table class = "collection_table">
<tbody>
    <tr></tr>
    <tr id="row_"></tr>
    <tr id="row_"></tr>
    <tr id="row_"></tr>
    <tr id="row_"></tr>
    <!--snip-->
    <tr id="row_"></tr>
    <tr id="row_"></tr>
    <tr id="row_"></tr>
</tbody>
</table>

请注意,除了第一行(标题)之外的每一行都具有相同的 id,并且没有额外的数据将其标记为唯一行。

我的(当前)代码如下:

def bgg_scrape_rank_page(browser, bgg_data):
    time.sleep(1)
    table = browser.find_element_by_xpath("//table[@class='collection_table']/tbody")
    row = table.find_element_by_xpath("//tr[@id='row_']")
    while row:
        rank = row.find_element_by_xpath("//td[1]").text
        game_name = row.find_element_by_xpath("//td[3]/div[2]/a").text
        game_page = row.find_element_by_xpath("//td[3]/div[2]/a").get_attribute("href")
        print rank, game_name, game_page
        row = row.find_element_by_xpath("//following-sibling::tr")

我也尝试过使用迭代

rows = browser.find_elements_by_xpath("/tr[@id='row_']")
for row in rows:
    rank = row.find_element_by_xpath("//td[1]").text
    game_name = row.find_element_by_xpath("//td[3]/div[2]/a").text
    game_page = row.find_element_by_xpath("//td[3]/div[2]/a").get_attribute("href")
    print rank, game_name, game_page

问题是,无论我尝试什么,我总是只打印出第一行。只是一行一行的

1 "Pandemic Legacy: Season 1 https://boardgamegeek.com/boardgame/161936/pandemic-legacy-season-1".

【问题讨论】:

    标签: python selenium xpath


    【解决方案1】:

    问题在于您的XPath:您需要将点添加为.// 以指向您要应用XPath 的确切上下文,而不是始终指向&lt;html&gt;//。所以试试

    def bgg_scrape_rank_page(browser, bgg_data):
    time.sleep(1)
    table = browser.find_element_by_xpath("//table[@class='collection_table']/tbody")
    row = table.find_element_by_xpath(".//tr[@id='row_']")
    while row:
        rank = row.find_element_by_xpath(".//td[1]").text
        game_name = row.find_element_by_xpath(".//td[3]/div[2]/a").text
        game_page = row.find_element_by_xpath(".//td[3]/div[2]/a").get_attribute("href")
        print rank, game_name, game_page
        row = row.find_element_by_xpath(".//following-sibling::tr")
    

    【讨论】:

    • 谢谢!知道为什么我之前仍然得到一个大小为 100 的“行”列表,当时每个元素都相同吗?
    • XPath //tr[@id='row_'] 匹配页面上所有带有id='row_'tr 元素。这似乎是一个开发问题,因为 id 必须是唯一标识符,应该只设置为单个元素。在您的情况下,您可能需要使用索引来识别每个元素...
    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 2021-12-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多