如何在Python中与硒具有相同相对XPATH的两个表格区分
我正在尝试从IMDB(python中的 selenium
)刮擦一些数据,但我有问题。对于每部电影,我都必须找董事和作家。这两个元素都包含在两个表中,并且它们具有相同的 @Class
。当我刮擦时,我需要区分两张桌子,否则有时该程序可以作为导演提供作家,反之亦然。
我尝试使用相对 xpath
与该XPath一起查找所有元素(表),然后将它们放在循环中,我尝试将它们区分开来(即 H4 < /code>元素)和
先前的兄弟姐妹
函数。该代码有效,但找不到任何东西(每次返回 nan
)。
这是我的代码:
counter = 1
try:
driver.get('https://www.imdb.com/title/' + tt + '/fullcredits/?ref_=tt_cl_sm')
ssleep()
tables = driver.find_elements(By.XPATH, '//table[@class="simpleTable simpleCreditsTable"]/tbody')
counter = 1
for table in tables:
xpath_table = f'//table[@class="simpleTable simpleCreditsTable"]/tbody[{counter}]'
xpath_h4 = xpath_table + "/preceding-sibling::h4[1]/text()"
table_title = driver.find_element(By.XPATH, xpath_h4).text
if table_title == "Directed by":
rows_director = table.find_elements(By.CSS_SELECTOR, 'tr')
for row in rows_director:
director = row.find_elements(By.CSS_SELECTOR, 'a')
director = [x.text for x in director]
if len(director) == 1:
director = ''.join(map(str, director))
else:
director = ', '.join(map(str, director))
director_list.append(director)
counter += 1
except NoSuchElementException:
# director = np.nan
director_list.append(np.nan)
你们中的任何人都可以告诉我为什么它不起作用吗?也许有一个更好的解决方案。我希望您的帮助。
(在这里您可以找到我需要刮擦的页面的示例:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 imdb.com 您必须诱导 webdriverwait “ https://stackoverflow.com/a/64770041/7429447”> visibility_of_all_elements_located() ,您可以使用以下 定位器策略 :
使用 css_selector ::
使用 xpath :
控制台输出:
注意:您必须添加以下导入:
To extract the names and directors and writers of each movie within an imdb.com you have to induce WebDriverWait for visibility_of_all_elements_located() and you can use the following locator strategies:
Using CSS_SELECTOR:
Using XPATH:
Console Output:
Note : You have to add the following imports :
您可以使用
Directors
的h4
标记的id
属性 和Writers
来提取数据。尝试如下:
输出:
You can use the
id
attribute ofh4
tags of theDirectors
andWriters
to extract the data.Try like below:
Output:
由于它是静态页面内容,因此您甚至不需要硒。您可以使用轻量级 python requests 模块和 Bs4。这只是另一种方法。
输出:
Since it is static page content you don't even need selenium. you can use light weight python requests module and Bs4.It just an another approach.
Output: