Python can';无法从SPAN标记获取文本
我试图解析的网站结构如下所示:Python can';无法从SPAN标记获取文本,python,html,parsing,web-scraping,beautifulsoup,Python,Html,Parsing,Web Scraping,Beautifulsoup,我试图解析的网站结构如下所示: <table border="0" cellpadding="3" cellspacing="0" width="100%"> <tr height="25"> <td class="th" style="border:none" width="2%"> </td> <td class="th">movie</td> <td cla
<table border="0" cellpadding="3" cellspacing="0" width="100%">
<tr height="25">
<td class="th" style="border:none" width="2%"> </td>
<td class="th">movie</td>
<td class="th"> </td>
<td class="th"> </td>
</tr>
<tr id="place_1">
<td style="color: #555; vertical-align: top; padding: 6px">
<a name="1"></a>1.
</td>
<td style="height: 27px; vertical-align: middle; padding: 6px 30px 6px 0">
<a class="all" href="/326/">MOVIE TITLE IN SPANISH</a>
<br/>
<span class="text-grey">MOVIE TITLE IN ENGLISH</span>
</td>
<td style="width: 85px">
<div style="width: 85px; position: relative">
<a class="continue" href="/326/votes/">
9.191
</a>
<span style="color: #777">
(592 184)
</span>
</div>
</td>
</tr>
...
...
...
我得到的错误是:
AttributeError:“非类型”对象没有属性“获取文本”
或
'eng_title':信息[1]。span.text AttributeError:'NoneType'对象具有
没有“文本”属性
我认为你应该使用
应该有效。尝试以下方法。另外,检查您的soup变量,因为我可以毫无问题地运行您的代码。我怀疑在HTML的后面的某个地方,您没有一个这样的代码连续出现
如果类名一致,则可以使用bs4 4.7.1仅筛选具有相应类型元素的符合条件的行
for row in table.select('tr :has(span.text-grey):has(a.all)'):
movies.append({
'spn_title' : row.select_one('.all').text,
'eng_title' : row.select_one('.text-grey').text
})
print(movies)
否则,如果不存在,您需要一种处理方法。比如说,
for row in table.find_all('tr')[1:]:
movies.append({
'spn_title' : row.select_one('.all').text if row.select_one('.all') is not None else 'None',
'eng_title' : row.select_one('.text-grey').text if row.select_one('.text-grey') is not None else 'None'
})
print(movies)
'eng_title':信息[1]。getElementsByTagName('span')[0]。innerHTML TypeError:'NoneType'对象不可调用。仅供参考,您可以稍微压缩该选择器。
tr:has(span.text-grey,a.all)
<代码>:has()接受一个相对选择器列表。第一个解决方案返回重复的行,因此每个电影打印两次。第二个解决方案正是我想要的。非常感谢你!!!但是span标签到底有什么问题呢?我怀疑您在某些情况下选择的是不存在项目的情况
for row in table.select('tr :has(span.text-grey):has(a.all)'):
movies.append({
'spn_title' : row.select_one('.all').text,
'eng_title' : row.select_one('.text-grey').text
})
print(movies)
for row in table.find_all('tr')[1:]:
movies.append({
'spn_title' : row.select_one('.all').text if row.select_one('.all') is not None else 'None',
'eng_title' : row.select_one('.text-grey').text if row.select_one('.text-grey') is not None else 'None'
})
print(movies)