ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

使用python bs4从onclick属性获取值

2019-10-30 12:56:41  阅读:511  来源: 互联网

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


我无法解析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 ''))

但这似乎不起作用.

解决方法:

您可以使用正则表达式从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']
...

希望能有所帮助.

标签:beautifulsoup,web-scraping,html-parsing,python,regex
来源: https://codeday.me/bug/20191030/1968078.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有