小编use*_*208的帖子

测试没有beautifulsoup python内容的标签

我正在使用Python中的BeautifulSoup来抓取网页.问题中的html如下所示:

<td><a href="blah.html>blahblah</a></td>
<td>line2</td>
<td></td>
Run Code Online (Sandbox Code Playgroud)

我想采取td标签的内容.所以对于第一个td,我需要"blahblah"文本,对于下一个td,我想写"line2",而对于最后一个td,"空白",因为没有内容.

我的代码片段看起来像这样 -

row = [] 
for each_td in td:                        
    link = each_td.find_all('a')                                                
    if link:
        row.append(link[0].contents[0])
        row.append(link[0]['href'])
    elif each_td.contents[0] is None:
        row.append('blank')                
    else:
        row.append(each_td.contents[0])
print row
Run Code Online (Sandbox Code Playgroud)

但是在运行时,我得到错误 -

elif each_td.contents[0] is None:
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

请注意 - 我正在使用beautifulsoup.

如何测试"no-content-td"和weite?为什么"......是无"不起作用?

python beautifulsoup

3
推荐指数
2
解决办法
5180
查看次数

如何在python beautifulsoup中加入工作

我正在学习python和beautifulsoup,并在网上看到了这段代码:

from BeautifulSoup import BeautifulSoup, SoupStrainer
import re

html = ['<html><body><p align="center"><b><font size="2">Table 1</font></b><table><tr><td>1. row 1, cell 1</td><td>1. row 1, cell 2</td></tr><tr><td>1. row 2, cell 1</td><td>1. row 2, cell 2</td></tr></table><p align="center"><b><font size="2">Table 2</font></b><table><tr><td>2. row 1, cell 1</td><td>2. row 1, cell 2</td></tr><tr><td>2. row 2, cell 1</td><td>2. row 2, cell 2</td></tr></table></html>']
soup = BeautifulSoup(''.join(html))
searchtext = re.compile(r'Table\s+1',re.IGNORECASE)
foundtext = soup.find('p',text=searchtext) # Find the first <p> tag with the search text
table = foundtext.findNext('table') # Find the first <table> tag that follows it …
Run Code Online (Sandbox Code Playgroud)

python beautifulsoup

2
推荐指数
1
解决办法
3221
查看次数

python正则表达式问题匹配td元素内的链接

我正在尝试使用正则表达式匹配表中的单元格,但问题不是所有单元格都遵循相同的模式.例如,td可以采用以下格式:

<td><a href="page101010.html">PageNumber</a></td>
Run Code Online (Sandbox Code Playgroud)

或这种格式:

<td align="left" ></td>
Run Code Online (Sandbox Code Playgroud)

基本上,td中的超链接部分并不存在,只是在某些部分.

我尝试使用下面的python正则表达式代码匹配这种情况,但它失败了.

match = re.search(r'<td align="left" ><?a?.+\>?(.+)\<?\/?a?\>?\<\/td\>', tdlink)
Run Code Online (Sandbox Code Playgroud)

我只需要'匹配'来找到上面()中包含的部分.但是我收到语法错误或无对象消息.

我哪里错了?

html python regex html-table

0
推荐指数
1
解决办法
350
查看次数

标签 统计

python ×3

beautifulsoup ×2

html ×1

html-table ×1

regex ×1