2017-08-30 59 views
1

我被困在试图从网站返回文本。我想从下面的例子中返回ownerId和unitId。任何帮助是极大的赞赏。如何使用python和BeautifulSoup无标签地从HTML返回文本?

<script> 
    h1.config.days = "7"; 
    h1.config.hours = "24"; 
    h1.config.color = "blue"; 
    h1.config.ownerId = 7321; 
    h1.config.locationId = 1258; 
    h1.config.unitId = "164"; 
</script> 
+0

由于这部分不是html,使用正则表达式来提取你想要的数据 – balki

回答

1

你可以使用Beautiful Soup像这样:

#!/usr/bin/env python 

from bs4 import BeautifulSoup 

html = ''' 
<script> 
    h1.config.days = "7"; 
    h1.config.hours = "24"; 
    h1.config.color = "blue"; 
    h1.config.ownerId = 7321; 
    h1.config.locationId = 1258; 
    h1.config.unitId = "164"; 
</script> 
''' 

soup = BeautifulSoup(html, "html.parser") 
jsinfo = soup.find("script") 

d = {} 
for line in jsinfo.text.split('\n'): 
    try: 
     d[line.split('=')[0].strip().replace('h1.config.','')] = line.split('=')[1].lstrip().rstrip(';') 
    except IndexError: 
     pass 

print 'OwnerId: {}'.format(d['ownerId']) 
print 'UnitId: {}'.format(d['unitId']) 

这将产生以下结果:

OwnerId: 7321 
UnitId: "164" 

而且这样你可以过访问任何其他变量,通过做d['variable']

更新的情况下,

现在你要处理多个<script>标签,通过这些迭代,你可以这样做:现在

jsinfo = soup.find_all("script") 

jsinfo<class 'bs4.element.ResultSet'>类型,你可以遍历像正常的列表

我们提取LATLON你可以简单地做:

#!/usr/bin/env python 

from bs4 import BeautifulSoup 
import requests 

url = 'https://www.your_url' 
# the user-agent you specified in the comments 
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17'} 

html = requests.get(url, headers=headers).text 
soup = BeautifulSoup(html, "html.parser") 
jsinfo = soup.find_all("script") 

list_of_interest = ['hl.config.lat', 'hl.config.lon'] 

d = {} 
for line in jsinfo[9].text.split('\n'): 
    if any(word in line for word in list_of_interest): 
     k,v = line.strip().replace('hl.config.','').split(' = ') 
     d[k] = v.strip(';') 

print 'Lat => {}'.format(d['lat']) 
print 'Lon => {}'.format(d['lon']) 

这将产生以下结果:

Lat => "28.06794" 
Lon => "-81.754349" 

通过list_of_interest附加更多的价值,你可以访问某些其他变量,如果你喜欢!

+0

谢谢你的回应。如果有多个,这是如何工作的? –

+0

@JustinHill,我更新了答案! – coder

+0

此外,我使用urllib.request.Request使用标题['User-Agent'] =“Mozilla/5.0(X11; Linux i686)AppleWebKit/537.17(KHTML,如Gecko)Chrome/24.0.1312.27 Safari/537.17” –

相关问题