【问题标题】:Python to get onclick valuesPython获取onclick值
【发布时间】:2014-12-10 21:00:25
【问题描述】:

我正在使用 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'])

我做错了什么?

【问题讨论】:

  • 对于您提供的输入,它会打印['LoremIpsum', 'FooWorld'],这就是您想要的,对吧?那么,问题是什么?请提供一个 HTML 输入,这会给您解析带来麻烦。谢谢。

标签: python web-scraping beautifulsoup


【解决方案1】:

试试这样:

>>> 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]

【讨论】:

  • 非常感谢您的代码,这是一个了不起的改进!这正是我需要的样子......但是,我的结果中仍然出现“searchDB”......我相信我会弄清楚如何删除它。
  • 沉默所有异常通常是不明智的做法。在这种情况下,KeyError 就足够了。
  • 如果你知道你在做什么,那么这不是问题,是的,我们不想要没有 onclick 属性的'a'标签
  • 我赞成你,因为它的价值。我仍在试图弄清楚如何从输出中解析这个该死的“searchDB”lol
  • @FairlightEvony 我也给出了解决方案
【解决方案2】:

试试这个

or row in rows[1:]: cols = row.findAll('td') link = cols[1].find('a').get('onclick')

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 1970-01-01
    • 2013-09-08
    • 2010-11-27
    • 2020-04-08
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多