Python,遍历 url 列表来解析 html 内容

标签 python beautifulsoup

下面是url的html来源:

<h1>Queue &lt;&lt;hotspot-00:26:BB:05:BB:10&gt;&gt; Statistics </h1>
<ul>
  <li>Source-addresses: 10.10.1.130
  <li>Destination-address: ::/0
  <li>Max-limit: 1.02Mb/2.04Mb (Total: <i>unlimited</i>)
  <li>Limit-at: 1.02Mb/2.04Mb (Total: <i>unlimited</i>)
  <li>Last update: Mon Sep 23 21:41:16 2019

</ul>

这是我的代码:

注意 linksurls

的列表
for link in links:
    page = requests.get(link).text
    sp1 = BeautifulSoup(page, "html.parser").findAll('h1')
    sp2 = BeautifulSoup(page, "html.parser").findAll('li')
    print(sp1,sp2)

当前输出

[<h1>Queue &lt;&lt;hotspot-00:26:BB:05:BB:10&gt;&gt; Statistics </h1>] [<li>Source-addresses: 10.10.1.130
  <li>Destination-address: ::/0
  <li>Max-limit: 1.02Mb/2.04Mb (Total: <i>unlimited</i>)
  <li>Limit-at: 1.02Mb/2.04Mb (Total: <i>unlimited</i>)
  <li>Last update: Tue Sep 24 00:27:05 2019

尝试编辑我的代码以获得以下输出。

hotspot-00:26:BB:05:BB:10, Limit-at: 1.02Mb/2.04Mb (Total: <i>unlimited

最佳答案

首先,您不需要创建两个 BeautifulSoup 对象。至于你的问题:

import re

for link in links:
    soup = BeautifulSoup(requests.get(link).content, "html.parser")
    header = soup.find('h1').text
    header = re.sub(r'.*<<(.*)>>.*', r'\g<1>', header)
    limit = [elem.text.strip() for elem in soup.find_all('li') if re.search(r'^Limit-at:', elem.text)][0].split('\n')[0]
    print(header, limit)

我使用您提供的 html 来测试上述解决方案。

所以您会在那里获取列表,因为您使用的是总是返回列表的 find_all

对于 header ,我使用了 find 相同的东西,但它只返回第一个匹配项。然后我进行一些正则表达式替换,以删除 header 测试所需部分以外的所有内容。

对于限制,事情有点棘手,因为它位于嵌套的 li 元素中。因此循环遍历所有 li 元素,添加文本属性以“Limit-at:”开头的元素。因为那将是一个列表,所以我捕获 0 元素,将其拆分为换行符,这会生成一个新列表。然后获取其中的零元素以删除该文本的“上次更新”部分。

关于Python,遍历 url 列表来解析 html 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58070822/

相关文章:

python - 使用 TF1 读取由 TF2 创建的 protobuf

python - BeautifulSoup tag.children 只获取奇数元素

javascript - Python BeautifulSoup html.parser 不工作

python - 关于python3.6当我导入bs4时,不起作用

python - 未实现错误 : Learning rate schedule must override get_config

python - 列表列表更改意外地反射(reflect)在子列表中

Python数据帧如何获取重复计数> 1的行

python beautiful-soap json - 抓取一页但不抓取其他类似的页面

python - 使用 BeautifulSoup 制作 requests.post 来访问子页面?

python - python中的异步I/O是什么?