- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试从 The Wealth of Nations 的在线版本中提取文本并创建一个数据框,其中每个观察结果都是书中的一页。我以一种迂回的方式来做,试图模仿我在 R 中所做的类似的事情,但我想知道是否有一种方法可以直接在 BeautifulSoup 中做到这一点。
我所做的是首先从页面中获取整个文本:
import pandas as pd
import requests
from bs4 import BeautifulSoup
import re
r = requests.get('https://www.gutenberg.org/files/38194/38194-h/38194-h.htm')
soup = BeautifulSoup(r.text,'html.parser')
但从现在开始,我只使用正则表达式和文本。我找到了本书文本的开头和结尾:
beginning = [a.start() for a in re.finditer(r"BOOK I\.",soup.text)]
beginning
end = [a.start() for a in re.finditer(r"FOOTNOTES",soup.text)]
book = soup.text[beginning[1]:end[0]]
然后我删除回车符和换行符并分割成“[Pg digits]”形式的字符串并将所有内容放入 pandas 数据框中。
book = book.replace('\r',' ').replace('\n',' ')
l = re.compile('\[[P|p]g\s?\d{1,3}\]').split(book)
df = pd.DataFrame(l,columns=['col1'])
df['page'] = range(2,df.shape[0]+2)
HTML 代码中有页码指示器,形式为 <span class='pagenum'><a name="Page_vii" id="Page_vii">[Pg vii]</a></span>
.有没有一种方法可以通过在这些“跨度”之间搜索文本来在 BeautifulSoup 中进行文本提取?我知道如何使用 findall 搜索页面标记,但我想知道如何提取这些标记之间的文本。
最佳答案
要获取页面标记和与之关联的文本,您可以使用 bs4
和 re
。为了匹配两个标记之间的文本,可以使用 itertools.groupby
:
from bs4 import BeautifulSoup as soup
import requests
import re
import itertools
page_data = requests.get('https://www.gutenberg.org/files/38194/38194-h/38194-h.htm').text
final_data = [(i.find('a', {'name':re.compile('Page_\w+')}), i.text) for i in soup(page_data, 'html.parser').find_all('p')]
new_data = [list(b) for a, b in itertools.groupby(final_data, key=lambda x:bool(x[0]))][1:]
final_data = {new_data[i][0][0].text:'\n'.join(c for _, c in new_data[i+1]) for i in range(0, len(new_data), 2)}
输出(样本,SO格式实际结果太长):
{'[Pg vi]': "'In recompense for so many mortifying things, which nothing but truth\r\ncould have extorted from me, and which I could easily have multiplied to a\r\ngreater number, I doubt not but you are so good a christian as to return good\r\nfor evil, and to flatter my vanity, by telling me, that all the godly in Scotland\r\nabuse me for my account of John Knox and the reformation.'\nMr. Smith having completed, and given to the world his system of\r\nethics, that subject afterwards occupied but a small part of his lectures.\r\nHis attention was now chiefly directed to the illustration of\r\nthose other branches of science which he taught; and, accordingly, he\r\nseems to have taken up the resolution, even at that early period, of\r\npublishing an investigation into the principles of what he considered\r\nto be the only other branch of Moral Philosophy,—Jurisprudence, the\r\nsubject of which formed the third division of his lectures. At the\r\nconclusion of the Theory of Moral Sentiments, after treating of the\r\nimportance of a system of Natural Jurisprudence, and remarking that\r\nGrotius was the first, and perhaps the only writer, who had given any\r\nthing like a system of those principles which ought to run through,\r\nand be the foundation of the law of nations, Mr. Smith promised, in\r\nanother discourse, to give an account of the general principles of law\r\nand government, and of the different revolutions they have undergone\r\nin the different ages and periods of society, not only in what concerns\r\njustice, but in what concerns police, revenue, and arms, and whatever\r\nelse is the object of law.\nFour years after the publication of this work, and after a residence\r\nof thirteen years in Glasgow, Mr. Smith, in 1763, was induced to relinquish\r\nhis professorship, by an invitation from the Hon. Mr. Townsend,\r\nwho had married the Duchess of Buccleugh, to accompany the\r\nyoung Duke, her son, in his travels. Being indebted for this invitation\r\nto his own talents alone, it must have appeared peculiarly flattering\r\nto him. Such an appointment was, besides, the more acceptable,\r\nas it afforded him a better opportunity of becoming acquainted with\r\nthe internal policy of other states, and of completing that system of\r\npolitical economy, the principles of which he had previously delivered\r\nin his lectures, and which it was then the leading object of his studies\r\nto perfect.\nMr. Smith did not, however, resign his professorship till the day\r\nafter his arrival in Paris, in February 1764. He then addressed the\r\nfollowing letter to the Right Honourable Thomas Millar, lord advocate\r\nof Scotland, and then rector of the college of Glasgow:—", '[Pg vii]': "His lordship having transmitted the above to the professors, a meeting\r\nwas held; on which occasion the following honourable testimony\r\nof the sense they entertained of the worth of their former colleague\r\nwas entered in their minutes:—\n'The meeting accept of Dr. Smith's resignation in terms of the above letter;\r\nand the office of professor of moral philosophy in this university is therefore\r\nhereby declared to be vacant. The university at the same time, cannot\r\nhelp expressing their sincere regret at the removal of Dr. Smith, whose distinguished\r\nprobity and amiable qualities procured him the esteem and affection\r\nof his colleagues; whose uncommon genius, great abilities, and extensive\r\nlearning, did so much honour to this society. His elegant and ingenious\r\nTheory of Moral Sentiments having recommended him to the esteem of men\r\nof taste and literature throughout Europe, his happy talents in illustrating\r\nabstracted subjects, and faithful assiduity in communicating useful knowledge,\r\ndistinguished him as a professor, and at once afforded the greatest pleasure,\r\nand the most important instruction, to the youth under his care.'\nIn the first visit that Mr. Smith and his noble pupil made to Paris,\r\nthey only remained ten or twelve days; after which, they proceeded\r\nto Thoulouse, where, during a residence of eighteen months, Mr. Smith\r\nhad an opportunity of extending his information concerning the internal\r\npolicy of France, by the intimacy in which he lived with some of\r\nthe members of the parliament. After visiting several other places in\r\nthe south of France, and residing two months at Geneva, they returned\r\nabout Christmas to Paris. Here Mr. Smith ranked among his\r\nfriends many of the highest literary characters, among whom were\r\nseveral of the most distinguished of those political philosophers who\r\nwere denominated Economists."}
关于python - BeautifulSoup 页码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49348263/
HTML 在 div 中包含字符串: 'div class="slide"' 'img src="xttps://site.com/files/r_1000,kljg894/43k5j/35h43jk
我用这个方法 allcity = dom.body.findAll(attrs={'id' : re.compile("\d{1,2}")}) 返回这样的列表: [掳虏驴碌路驴碌脴虏煤脨脜脧垄脥酶 隆
我正在使用 Jupyter 笔记本、Python 3.5 和虚拟环境。 在我的虚拟环境中,我做了: (venv) > pip install BeautifulSoup4 这似乎运行良好 b/c 终端
我打算用 GUI 制作一个字典程序,但我在第一个障碍上就失败了。我刚刚安装了一个模块( PyDictionary ),但是当我运行以下代码时出现错误。 from PyDictionary import
我正在将一些解析器从 BeautifulSoup3 迁移到 BeautifulSoup4,我认为考虑到 lxml 非常快并且它是我在 BS4 中使用的解析器,分析它会变得多快是个好主意,这里是分析结果
这个问题在这里已经有了答案: Getting Python error "from: can't read /var/mail/Bio" (6 个答案) 关闭 11 个月前。 From Beauti
目前我无法输入这个,因为根据 top,我的处理器是 100%,我的内存是 85.7%,都被 python 占用了。 为什么?因为我让它通过一个 250 兆的文件来删除标记。 250兆,就是这样!我一直
我写了下面的代码: from bs4 import BeautifulSoup import sys # where is the sys module in the source code fold
通常,当我尝试使用BeautifulSoup解析网页时,BeautifulSoup函数会得到NONE结果,否则就会引发AttributeError。。以下是一些独立的(即,由于数据是硬编码的,不需要访
通常,当我尝试使用BeautifulSoup解析网页时,BeautifulSoup函数会得到NONE结果,否则就会引发AttributeError。。以下是一些独立的(即,由于数据是硬编码的,不需要访
我正在为一个项目使用 BeautifulSoup。这是我的 HTML 结构 John Sam Bailey Jack
这段代码正确地从我的博客中提取了马拉地语文本。我很欣赏使用漂亮的汤和正则表达式是多么容易。 from bs4 import BeautifulSoup import requests, re url
我想获取 HTML 中隐藏输入字段的值。 我想用 Python 编写一个正则表达式,它将返回 fooId 的值,前提是我知道 HTML 中的行遵循以下格式 有人可以提供一个 Python 示例来解
BeautifulSoup(bs4) BeautifulSoup是python的一个库,最主要的功能是从网页爬取数据,官方是这样解释的:BeautifulSoup提供一些简单,python式函
我正在尝试获取特定月份的所有链接、标题和日期,例如网站上的三月,我正在使用 BeautifulSoup 这样做: from bs4 import BeautifulSoup import reques
我正试图通过此链接收集有关 2020 年世界上收入最高的运动员收入的信息 https://www.forbes.com/profile/roger-federer/?list=athletes这是第一
我正在尝试从带有美丽汤的网页中捕获所有相关链接。我需要的所有链接都有 class="btn btn-gray"还有文字 More Info<> 仅提取这些链接的最佳方法是什么? 最佳答案 这个怎么样?
我正在尝试抓取一个具有下拉菜单的站点,用户可以在其中选择要显示的数据的年份。但是,我似乎被困在我的实现中。 这是网站网址:https://www.pgatour.com/tournaments/mas
我正在使用 BeautifulSoup 和 mechanise 从网页中查找一些内容。问题是有时找不到我正在寻找的字符串。我不知道有什么问题 对于许多网页,它可以正常工作数月,但突然停止工作。然后我必
( 更新代码 就在下面) 我有一个类:UrlData , 生成一个 url 列表: for url in urls: rawMechSiteInfo = mech.open(url) #me
我是一名优秀的程序员,十分优秀!