我知道您正在尝试使用 selenium 来实现这一目标。但更有效的是使用requests 和beautifulsoup 库。它们适用于 2.7 和 3.x 版本的 Python。
您的问题的简单示例:
好的,html 看起来像这样:
<tr class="company"></tr>
<tr class="person">..</tr>
<tr class="person">..</tr>
<tr class="person">..</tr>
<tr class="company"></tr>
<tr class="person">..</tr>
<tr class="company"></tr>
<tr class="person">..</tr>
<tr class="person">..</tr>
<tr class="company">..</tr>
我之前的代码:
import requests
from bs4 import BeautifulSoup
response = requests.get(yourUrl)
soup = BeautifulSoup(response.text, 'html.parser')
companyPersons = {}
for company in soup.find_all('tr',{'class': 'company'}): # find all class'es with company
for person in company.children: # finds all children tags, e.g. company has 2 childrens person1 and person2, so it will find both
if company in companyPersons:
companyPersons[company].append(person)
else:
companyPersons[company] = person
编辑到上一个答案
我已经检查了 html 以及需要得到什么。嗯,方法和我之前写的很相似,只是稍作调整。
test_dict = {}
for company in soup.find_all('tr', {'class': 'regroworg'}):
for child in company.find_all('span', {'class': 'regorgname'}):
for person in company.find_next_siblings('tr', {'class': 'regrow'} != {'class': 'regroworg'}):
if person['class'] != company['class']:
if child.text not in test_dict:
test_dict[child.text] = [person.text]
else:
test_dict[child.text].append(person.text)
else:
break
上面的代码就像你写的那样工作。它应该抓住所有公司的人。代码{'class': 'regrow'} != {'class': 'regroworg'} 中的这一部分正在为找到所需的兄弟姐妹做所有的魔法。
结果将与此类似:
test_dict['ABB Secheron Ltd.']
['\nMr. Emmanuel Mittay, Key Account Manager\nemmanuel.mittay@ch.abb.com\n41 58 586 25 09\n41 58 586 22 28']
现在您可以将数据写入 .CSV 或其他任何位置。
解决当前问题的代码存在一些问题
当然我认为从性能角度来看它可以做得更好,但对于当前的问题应该没问题。我注意到大约有 607 家公司(但我不是 100% 确定这个数字),但我的代码提取了 396 个字典键(例如,那是公司的)。所以我建议调试代码并修复它。但我认为代码至少解决了你 50% 的问题,现在只需修复它,让你自己 100% 解决它(我认为这很容易解决)。 ;)