【问题标题】:How can I pass a CSS selector with IDs or class names in R html_nodes?如何在 R html_nodes 中传递带有 ID 或类名的 CSS 选择器?
【发布时间】:2019-12-18 10:51:16
【问题描述】:

我正在尝试从德国议会的主页中提取议会成员的姓名,但是,无论我尝试使用哪个 css 选择器或 xpath,它都不会返回任何内容。

https://www.bundestag.de/ausschuesse/a11#

#names <- landing_page_AS %>%
#html_nodes("main > div") %>% 
#extract2(7) %>%
#html_nodes("h3") %>%
#html_text()

names <- landing_page_AS %>% 
html_nodes(".bt-teaser-person-text h3") %>%
#html_nodes(xpath = "//*[(@id = "bt-collapse-538348")]//h3") %>%
#html_nodes(xpath = "//*[contains(concat( " ", @class, " " ), 
concat( " ", "bt-teaser-person-text", " " ))]//h3") %>% 
html_text()

【问题讨论】:

    标签: html r xpath web-scraping css-selectors


    【解决方案1】:

    我能够使用 selenium 从德国议会网站中提取姓名列表。问题可能是服务器拒绝访问您的机器人而不使用无头浏览器。

    如果你使用 selenium,这是你可以使用的代码和 xpath,对我有用:

    from selenium import webdriver
    chrome_options = webdriver.ChromeOptions()
    driver = webdriver.Chrome(r"your_webdriver_address", chrome_options = chrome_options)
    
    #OPEN NEW BROWSER
    driver.set_page_load_timeout(10)
    
    driver.get('https://www.bundestag.de/en/members')
    
    button = driver.find_elements_by_xpath("//*[contains(@class, 'icon-list-bullet')]")
    button = button[0]
    button.click()
    time.sleep(3)
    GE_MEMBERS_NAMES = driver.find_elements_by_xpath("//*[contains(@class, 'bt-teaser-person-text')]/h3")
    
    for item in GE_MEMBERS_NAMES:
        name = item.text
        print (name)
    

    【讨论】:

    • 很高兴它有帮助:)(如果您觉得它有帮助,请不要犹豫,点赞或接受答案):)
    猜你喜欢
    • 2011-07-06
    • 2020-12-05
    • 2011-05-04
    • 1970-01-01
    • 2016-08-24
    • 2015-09-13
    • 2017-10-08
    • 2012-04-24
    • 1970-01-01
    相关资源
    最近更新 更多