【发布时间】:2021-07-19 22:18:51
【问题描述】:
我目前正在开发一些代码来从网站上抓取文本。我不想刮掉整个页面,而只是刮掉包含某些单词的页面部分。对于大多数使用 .find_all("p") 命令的 URL,我已经设法做到了这一点,但这不适用于定向到 PDF 的 URL。
我似乎找不到将 PDF 作为文本打开然后将文本分成段落的方法。这就是我想做的事情:首先 1)将 PDF 嵌入 URL 作为文本打开,2)将此文本分成多个段落。这样,我可以只抓取包含某些单词的段落。
下面是我目前用来为“普通”网址抓取包含某些单词的段落的代码。非常感谢任何使这项工作适用于 PDF 嵌入式 URL 的提示(例如变量 'url2',下面的代码)!
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import re
url1 = "https://brainybackpackers.com/best-places-for-whale-watching-in-the-world/"
url2 = "https://www.environment.gov.au/system/files/resources/7f15bfc1-ed3d-40b6-a177-c81349028ef6/files/aust-national-guidelines-whale-dolphin-watching-2017.pdf"
url = url1
req = Request(url, headers={"User-Agent": 'Mozilla/5.0'})
page = urlopen(req, timeout = 5) # Open page within 5 seconds. This line skips 'empty' websites
htmlParse = BeautifulSoup(page.read(), 'lxml')
SearchWords = ["orca", "killer whale", "humpback"] # text must contain these words
# Check if the article text mentions the SearchWord(s). If so, continue the analysis.
if any(word in htmlParse.text for word in SearchWords):
textP = ""
text = ""
# Look for paragraphs ("p") that contain a SearchWord
for word in SearchWords:
print(word)
for para in htmlParse.find_all("p", text = re.compile(word)):
textParagraph = para.get_text()
textP = textP + textParagraph
text= text + textP
print(text)
【问题讨论】:
-
您可以在不保存到磁盘的情况下阅读和搜索 PDF。看我的例子
标签: python pdf web-scraping nlp