Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取对twitter iframe中html元素的访问,而不使用src属性_Python_Web Scraping_Beautifulsoup - Fatal编程技术网

Python 获取对twitter iframe中html元素的访问,而不使用src属性

Python 获取对twitter iframe中html元素的访问,而不使用src属性,python,web-scraping,beautifulsoup,Python,Web Scraping,Beautifulsoup,我一直在使用Python和Beautifulsoup4从非全局网站中获取数据。那边的一些公司,比如这家: 拥有推特账户。我想访问twitter帐户的名称。问题是它位于没有src属性的iframe内部。我知道iframe是由不同于网站其余部分的请求调用的,但我现在想知道,在不显示src属性的情况下是否有可能访问它?您可以使用selenium来完成此操作。以下是完整的代码: from selenium import webdriver from selenium.webdriver.support.

我一直在使用Python和Beautifulsoup4从非全局网站中获取数据。那边的一些公司,比如这家:
拥有推特账户。我想访问twitter帐户的名称。问题是它位于没有src属性的iframe内部。我知道iframe是由不同于网站其余部分的请求调用的,但我现在想知道,在不显示src属性的情况下是否有可能访问它?

您可以使用
selenium
来完成此操作。以下是完整的代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

url = "https://www.unglobalcompact.org/what-is-gc/participants/2968-Orsted-A-S "

driver = webdriver.Chrome()

driver.get(url)

iframe = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="twitter-widget-0"]')))

driver.switch_to.frame(iframe)

names = driver.find_elements_by_xpath('//*[@class="TweetAuthor-name Identity-name customisable-highlight"]')

names = [name.text for name in names]
 
try:
    name = max(set(names), key=names.count)  #Finds the most frequently occurring name. This is because the same author has also retweeted tweets made by others. These retweets would contain the name of other people. The most frequently occurring name is the name of the author.
    print(name)

except ValueError:
    print("No Twitter Feed Found!")

driver.close()
输出:

Ørsted

谢谢你的帮助。我还有一个问题:如何检查WebElement是否为空?我知道如何检查它是否存在,但这很简单。至于你的问题,空是什么意思?我想找到了一个更简单的解决方案。我不需要删除被禁止的帐户,所以我只需要通过xpath(“html/body/div”)检查find_元素的长度,如果为0,则表示该帐户被禁止,因为body标记中没有任何内容。无论如何,感谢您的帮助