通过 Selenium 解码 facebook 上的 Class 个名字

Decoding Class names on facebook through Selenium

我注意到 facebook 有一些奇怪的 class 名字看起来像是计算机生成的。我不知道这些 classes 是否至少随着时间的推移保持不变,或者它们在某个时间间隔内发生变化?也许有这方面经验的人可以回答。我唯一能看到的是,当我退出 Chrome 并再次打开它时,它仍然是一样的,所以至少它们不会改变每个浏览器会话。

所以我猜想抓取 facebook 的最佳方法是在用户界面中使用一些元素并假设结构始终相同,例如从“关于”部分获取地址,如下所示:

from selenium import webdriver
driver = webdriver.Chrome("C:/chromedriver.exe")

driver.get("https://www.facebook.com/pg/Burma-Superstar-620442791345784/about/?ref=page_internal")
# wait some time
address_elements = driver.find_elements_by_xpath("//span[text()='FIND US']/../following-sibling::div//button[text()='Get Directions']/../../preceding-sibling::div[1]/div/span")
for item in address_elements:
    print item.text

你说得很对。 Facebook is built through ReactJS which is pretty much evident from the presence of the following keywords and tags within the HTML DOM:

  • {"react_render":true,"reflow":true}
  • <!-- react-mount-point-unstable -->
  • ["React-prod"]
  • ["ReactDOM-prod"]
  • ReactComposerTaggerType:{r:["t5r69"],be:1}

因此,动态生成的class名称必然会在某些时间间隔后发生变化。


解决方案

解决方案是使用 static 属性构造一个 dynamic .

要检索正文FIND US下方地址的第一行,您需要归纳WebDriverWait in conjunction with expected_conditions as visibility_of_element_located(),您可以使用以下优化解决方案:

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[normalize-space()='FIND US']//following::span[2]"))))

参考资料

您可以在以下位置找到一些相关讨论:


结尾

Note: Scraping Facebook violates their Terms of Service of section 3.2.3 and you are liable to be questioned and may even land up in Facebook Jail. Use Facebook Graph API instead.