【问题标题】:Get values from onclick attribute using python bs4使用python bs4从onclick属性中获取值
【发布时间】:2013-09-08 03:09:11
【问题描述】:

我无法解析 onclick 属性以仅获取选定的值。这是onclick属性

onclick="try{appendPropertyPosition(this,'B10331465','9941951739','','Dealer','Murugan.N');jsb9onUnloadTracking();jsevt.stopBubble(event);}catch(e){};"

如何仅从该 onclick 属性中获取选定的值,例如 (phonenumber , '', 'Dealer','Name')。这是我的代码。

from bs4 import BeautifulSoup
import urllib2
import re
url="http://www.99acres.com/property-in-velachery-chennai-south-ffid?"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
properties = soup.findAll('a', title=re.compile('Bedroom'))
for eachproperty in properties:
 print "http:/"+ eachproperty['href']+",", eachproperty.string, eachproperty['onclick']

更新

我只想从上面提到的onclick 属性中获取一个电话号码,虽然有很多。

例如,现在我得到了

Y10765227, 9884877926, 9283183326,, Dealer, Rgmuthu
L10038779, 9551154555, ,, ,
R10831945, 9150000747, 9282109134, 9043728565, ,, ,
B10750123, 9952946340, , Dealer, Bala
R10763559, 9841280752, 9884797013, , Dealer, Senthil

这是我通过使用以下代码得到的

re.findall("'([a-zA-Z0-9,\s]*)'", (a['onclick'] if a else ''))

我正在尝试以仅检索一个电话号码而其余的电话号码消失的方式进行修改。它应该是这样的

    Y10765227, 9884877926, Dealer, Rgmuthu
    L10038779, 9551154555
    R10831945, 9150000747
    B10750123, 9952946340, Dealer, Bala
    R10763559, 9841280752, Dealer, Senthil

我正在尝试使用

re.findall("'([a-zA-Z0-9,\s]*)'", (re.sub(r'([^,]+,[^,]+,)(.*?)([A-Za-z].*)', r'\1\0',a['onclick']) if a else ''))

但这似乎不起作用。

【问题讨论】:

    标签: python regex web-scraping html-parsing beautifulsoup


    【解决方案1】:

    您可以使用正则表达式从onclick 中获取数据:

    properties = soup.findAll('a', title=re.compile('Bedroom'))
    for eachproperty in properties:
        print re.findall("'([a-zA-Z0-9,\s]*)'", eachproperty['onclick'])
    

    打印:

    ['Y10765227', '9884877926, 9283183326', '', 'Dealer', 'Rgmuthu']
    ['L10038779', '9551154555', ',', ',']
    ['R10831945', '9150000747, 9282109134, 9043728565', ',', ',']
    ['B10750123', '9952946340', '', 'Dealer', 'Bala']
    ['R10763559', '9841280752, 9884797013', '', 'Dealer', 'Senthil']
    ...
    

    希望对您有所帮助。

    【讨论】:

    • 是的。有效。但我不想要第一个值,即:'Y10765227'。有什么办法可以撕掉吗?
    • 只需从 findall 中获取[1:] 切片。
    猜你喜欢
    • 2017-11-16
    • 2018-10-24
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多