python - 如何从抓取 Python 中填充空记录?
问题描述
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
r = requests.get('https://www.transfermarkt.com.br/esporte-clube-bahia/kader/verein/10010/saison_id/2019/plus/1', headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
impar = soup.find('table',{'class':'items'}).find_all('tr',{'class':'odd'})
bahia = []
for jog in impar:
nome = jog.find_all('tr')[0].img.get('alt')
posicao = jog.find_all('td',{'class':"zentriert"})[0].get('title')
idade = jog.find_all('td',{'class':"zentriert"})[1].text
nacionalidade = jog.find_all('td',{'class':"zentriert"})[2].img.get('alt')
altura = jog.find_all('td',{'class':"zentriert"})[3].text[0:-2]
pe = jog.find_all('td',{'class':"zentriert"})[4].text
desde =jog.find_all('td',{'class':"zentriert"})[5].text
clube_anterior = jog.find_all('td',{'class':'zentriert'})[6].img.get('alt')
preco_pago = jog.find_all('td',{'class':"zentriert"})[6].get('title')
contrato = jog.find_all('td',{'class':"zentriert"})[7].text
valor = jog.find('td',{'class':"rechts hauptlink"}).text[0:-4]
bahia.append((nome,posicao,idade,nacionalidade,altura,pe,desde,clube_anterior,preco_pago,contrato,valor))
我的问题是,我从中抓取的列表中的某些元素没有属性“clube_anterior”。当我尝试时impar[7].find_all('td',{'class':"zentriert"})[6]
,我得到一个错误(
,但是这段代码适用于我的大部分记录......无论如何我可以跳过在这个错误中产生的记录或然后用 NaN 或 None 填充?<td class="zentriert"></td>
impar[7].find_all('td',{'class':"zentriert"})[6].img.get('alt')
AttributeError: 'NoneType' object has no attribute 'get')
解决方案
将访问包装在try: except AttributeError:
.
您还无缘无故地一遍又一遍地重新查询 TD;我也重构了:
for jog in impar:
nome = jog.find_all("tr")[0].img.get("alt")
tds = jog.find_all("td", {"class": "zentriert"})
posicao = tds[0].get("title")
idade = tds[1].text
nacionalidade = tds[2].img.get("alt")
altura = tds[3].text[0:-2]
pe = tds[4].text
desde = tds[5].text
try:
clube_anterior = tds[6].img.get("alt")
except AttributeError:
clube_anterior = None
preco_pago = tds[6].get("title")
contrato = tds[7].text
valor = jog.find("td", {"class": "rechts hauptlink"}).text[0:-4]
bahia.append(
(
nome,
posicao,
idade,
nacionalidade,
altura,
pe,
desde,
clube_anterior,
preco_pago,
contrato,
valor,
)
)
推荐阅读
- java - Is there any way to apply dependency to one package only?
- python - 重命名无法识别的 Pandas 列
- c# - ASP.NET Core 依赖注入:在运行时传递参数
- javascript - How do I align th and td content of a table using Bootstrap 4?
- c++ - Running gcc 5.2 build on gcc 4.4.7 Red Hat 6.6
- mysql - MySQL 分组查询
- c# - c#,在子类中强制实现方法
- uitableview - 如何实现类似的过渡?
- makefile - makefile 定义中的逗号是什么意思?
- python - 如何忽略或修复 RuntimeWarning:编译时版本