python - BeautifulSoup无需页面结构即可获取数据

标签 python html beautifulsoup

这是网页:

<html>
<head>
<!--eBay V3- msxml 6.0 XXXXXXXXXXXXXXXXXXXXXXXXXX-->
<!--srcId - File Exchange Programmatically Upload-->
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<title>Upload File Programmatically</title><script language="JavaScript"><!--
                                                                var pageName = "File Exchange Upload";

                                                        //--></script><script language="javascript" src="http://include.ebaystatic.com/js/e867/us/legacy/globals_e8672us.js"> </script><script src="http://include.ebaystatic.com/js/e885/us/legacy/common_functions_e8852us.js"> </script></head>
<body>
                                File upload successful. Your ref # is 711103172.<br><a href="javascript:void(0);" onclick="self.close();return false;">Close</a></body>
</html>

我只需要提取数字711103172,BeautifulSoup适合这个吗?或者其他一些方法(我现在正在使用 BS,但是这个页面几乎没有结构。

我可以获取体内的数据来返回:

<body>
                                File upload successful. Your ref # is 711103172.<br><a href="javascript:void(0);" onclick="self.close();return false;">Close</a></body>

然而,一旦我到达那里,我就被困住了..

最佳答案

使用BeautifulSoup获取body文本,然后使用regular expressions提取所需的数字:

import re
from bs4 import BeautifulSoup

data = """
    Your HTML code here
"""

soup = BeautifulSoup(data, "html.parser")
match = re.search(r'Your ref # is (\d+)', soup.body.text)
print match.group(1) if match else 'Not Found'

打印:

711103172

仅供引用,正则表达式的 (\d+) 部分是 saving/capturing group\d+ 匹配一位或多位数字。

关于python - BeautifulSoup无需页面结构即可获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25517492/

相关文章:

python - QStyledItemDelegate 在QTableView中显示QComboBox

python - PyQt5 ListWidget 添加列表项

python - pandas 数据框列的不区分大小写匹配

html - 保持列表与文本内联,同时保持列表垂直定位

python - 使用 BeautifulSoup 解析嵌套的 HTML 列表

Python 子模块更简单的引用

html - 无需 JS 可点击的 css 菜单

html - Bootstrap 网格边界问题

带有漂亮汤的 Python 自定义 nagios 脚本 - 获取 "NRPE: Unable to read output"

python - 为什么它没有从 YouTube 获取任何 'a' 标签?