【问题标题】:How to return text from HTML without tag using python and BeautifulSoup?如何使用python和BeautifulSoup从没有标签的HTML返回文本?
【发布时间】:2017-08-30 20:28:44
【问题描述】:

我被困在试图从网站返回文本。我正在尝试从以下示例返回 ownerId 和 unitId。非常感谢任何帮助。

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

【问题讨论】:

  • 由于这部​​分不是html,所以使用regex提取你想要的数据

标签: python beautifulsoup urllib


【解决方案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'] 访问任何其他变量。

更新

现在,如果您必须处理多个 &lt;script&gt; 标签,您可以遍历它们:

jsinfo = soup.find_all("script")

现在,jsinfo&lt;class 'bs4.element.ResultSet'&gt; 的类型,您可以像普通 列表 一样对其进行迭代。

现在要提取 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 中附加更多值,您也可以根据需要访问其他一些变量!

【讨论】:

  • 感谢您的回复。如果有多个 ,这将如何工作?
  • 另外,我使用 urllib.request.Request 使用 headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0 .1312.27 Safari/537.17"
  • @JustinHill,是的,您实际引用的脚本与您发布的脚本完全不同,因此出现了 KeyError。我相应地更新了答案。结果也来自您在 cmets 中发布的网址,出于典型原因,我只是将其替换为答案。
  • 因为我在这里的声望低于 15,所以我无法给你一个重要的 +1。但是,我真的很感谢您的所有帮助。
猜你喜欢
  • 2014-11-17
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
相关资源
最近更新 更多