通过Python Selenium和Pandas抓取缺少属性的Web表



从网站上删除表格。但在这个过程中遇到了空细胞。下面的try except块最后把数据搞砸了。也不想排除完整的行,因为即使某些属性丢失,信息仍然是相关的。

try:
for i in range(10):
data = {'ID': IDs[i].get_attribute('textContent'),
'holder': holder[i].get_attribute('textContent'),
'view': view[i].get_attribute('textContent'),
'material': material[i].get_attribute('textContent'),
'Addons': addOns[i].get_attribute('textContent'),
'link': link[i].get_attribute('href')}
list.append(data)
except:
print('Error')

有什么想法吗?

您可以将要访问属性的所有对象放在这样的字典中:

objects={"IDs":IDs,"holder":holder,"view":view,"material":material...]

然后,您可以遍历该字典,如果特定属性不存在,只需在dict键对应的值上附加一个空字符串。类似这样的东西:

the_keys=list(objects.keys())
for i in range(len(objects["IDs"])): #I assume the ID field will never be empty
#so making a for loop like this is better since you iterate only through 
#existing objects
data={}

for j in range(len(objects)):
try:
data[the_keys[j]]=objects[the_keys[j]][i].get_attribute('textContent')
except Exception as e:
print("Exception: {}".format(e))
data[the_keys[j]]="" #this means we had an exception
#it is better to catch the specific exception that is thrown
#when the attribute of the element does not exist but I don't know what it is
list.append(data)

我不知道这段代码是否有效,因为我没有尝试过,但它应该能让你对如何解决问题有一个总体的想法。

如果您有任何问题、疑虑或顾虑,请直接询问。

编辑:要获得另一个对象的属性(如href(,只需包含一个if语句来检查键的值。我还意识到,您可以在对象字典中循环获取键和值,而不是通过索引访问每个键和值。你可以把内部循环改成这样:

for key,value in objects.items():
try:
if key=="link":
data[key]=objects[key][i].get_attribute("href")
else:
data[key]=objects[key][i].get_attribute("textContent")
except Exception as e:
print("Error: ",e)
data[key]=""

编辑2:

data={}
for i in list(objects.keys()):
data[i]=[]
for key,value in objects.items():
for i in range(len(objects["IDs"])):
try:
if key=="link":
data[key].append(objects[key][i].get_attribute("href"))
else:
data[key].append(objects[key][i].get_attribute("textContent"))
except Exception as e:
print("Error: ",e)
data[key].append("")

试试这个。您不必将数据字典附加到列表中。如果没有原始数据,我将无法提供更多帮助。我认为这应该奏效。

最新更新