【问题标题】:Facebook Selenium How can I get the number of likesFacebook Selenium 如何获得喜欢的次数
【发布时间】:2020-12-09 09:58:34
【问题描述】:

我正在尝试使用以下代码获取喜欢该帖子的人数。我尝试了两种方法都不起作用。它确实返回错误代码。

有人可以帮忙吗,不胜感激。

源代码: https://m.facebook.com/ufi/reaction/profile/browser/?ft_ent_identifier=3647203655325514

def get_likes(self):
    return self.driver.find_element_by_xpath('//span[@data-store="{"reactionType":1}"]/span/span').get_attribute("innerHTML")

def get_likes(self):
return self.driver.find_element_by_xpath('//span[@data-store="{\"reactionType\":1}"]/span/span').get_attribute("innerHTML")

语法错误:无法对“文档”执行“评估”:字符串 '//span[@data-store="{"reactionType":1}"]/span/span' 无效XPath 表达式。

【问题讨论】:

    标签: python selenium web-scraping error-handling


    【解决方案1】:

    还尝试以不同的方式进行转义,但结果相同 - 似乎 xpath 与 html 中的 " 存在问题,意味着它们已关闭,所以

    driver.find_element_by_xpath('//span[@id="u_0_r"]').get_attribute('data-store')

    只检测开口{

    div的ID是自动生成的,其中图标的位置按点击次数排序。

    您可以使用i 标记的class,直到有更好的解决方案,我真的很感兴趣:

    from selenium import webdriver
    driver = webdriver.Chrome(executable_path=r'C:\Program Files\ChromeDriver\chromedriver.exe')
    
    html_content = '''
    <div class="scrollAreaColumn">
            <span name="one" data-store="{"reactionType":1}">
             <span>133</span>
            </span>
            <span name="two" data-store="{"reactionType":1}">
             <i class="_2ep2 img sp_FnpQQMXWL5W sx_4760b1"></i>
             <span>128</span>
            </span>
            <span name="three" data-store="{"reactionType":1}">
             <i class="_2ep2 img sp_FnpQQMXWL5W sx_4760b1 xyz"></i>
             <span>128</span>
            </span>
    </div>       
    '''
    driver.get("data:text/html;charset=utf-8,{html_content}".format(html_content=html_content))
    count = driver.find_element_by_xpath('//i[@class="_2ep2 img sp_FnpQQMXWL5W sx_4760b1"]/following-sibling::span').text
    print(count)
    
    driver.close()
    

    【讨论】:

    • 宾果游戏,你是天才!!
    【解决方案2】:

    你可以试试这个 xpath:

    '//span[@data-store=\"{\'reactionType\':1}\"]//span[@data-sigil="reaction_profile_tab_count"]'
    

    【讨论】:

    • 欣赏这一点,但同样的错误信息。数据存储不是主要的 xpath 元素有问题吗?
    • 我编辑了xpath,我之前没有注意到它,它抱怨嵌套引号。
    • 现在试试看能不能返回结果。
    • 错误消息更改为 NoSuchElement,因为该元素带有“{\”reactionType\“:1}”。很有挑战性……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多