我正在使用 Python 和 BeautifulSoup 为我的一个小项目抓取网页。该网页有多个条目,每个条目由 HTML 中的表格行分隔。我的代码部分有效,但是很多输出是空白的,它不会从网页获取所有结果,甚至不会将它们收集到同一行中。
<html>
<head>
<title>Sample Website</title>
</head>
<body>
<table>
<td class=channel>Artist</td><td class=channel>Title</td><td class=channel>Date</td><td class=channel>Time</td></tr>
<tr><td>35</td><td>Lorem Ipsum</td><td><a href="#" onClick="searchDB('LoremIpsum','FooWorld')">FooWorld</a></td><td>12/10/2014</td><td>2:53:17 PM</td></tr>
</table>
</body>
</html>
我只想从 onclick 操作“searchDB”中提取值,因此例如“LoremIpsum”和“FooWorld”是我想要的唯一两个结果。
这是我编写的代码。到目前为止,它正确地提取了一些写入值,但有时这些值是空的。
response = urllib2.urlopen(url)
html = response.read()
soup = bs4.BeautifulSoup(html)
properties = soup.findAll('a', onclick=True)
for eachproperty in properties:
print re.findall("'([a-zA-Z0-9]*)'", eachproperty['onclick'])
我究竟做错了什么?
尝试这样:
>>> import re
>>> for x in soup.find_all('a'): # will give you all a tag
... try:
... if re.match('searchDB',x['onclick']): # if onclick attribute exist, it will match for searchDB, if success will print
... print x['onclick'] # here you can do your stuff instead of print
... except:pass
...
searchDB('LoremIpsum','FooWorld')
除了打印之外,您可以将其保存到某个变量中,例如
>>> k = x['onclick']
>>> re.findall("'(\w+)'",k)
['LoremIpsum', 'FooWorld']
\w
相当于 [a-zA-Z0-9]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)