gpt4 book ai didi

Python 从 URL 抓取 pdf

转载 作者:行者123 更新时间:2023-11-28 05:24:12 24 4
gpt4 key购买 nike

我想从 URL“http://www.nycgo.com/venues/thalia-restaurant#menu”中抓取文本我感兴趣的文本位于页面上的“菜单”选项卡中。我尝试使用 BeautifulSoup 获取页面上的所有文本,但以下代码的返回值丢失了菜单中的所有文本。

html = urllib2.urlopen("http://www.nycgo.com/venues/thalia-restaurant#menu")
html=html.read()
soup = BS(html)
print soup.get_text()

当我检查菜单内容中的元素时,菜单的内容似乎是页面上 html 的一部分。我确实注意到,当实际浏览页面时,菜单需要几秒钟才能完全加载。不确定这是否是上面的代码无法获取菜单内容的原因。

如有任何见解,我们将不胜感激。

最佳答案

虽然 soup.get_text() 从 HTML 文档(网页)返回所有文本,但这里的问题是菜单作为PDF,Beautiful soup 无法访问。实际的 PDF 文件在 Javascript 中定义如下:

{
name: "menu",
show: Boolean(1),
url: "/assets/files/programs/rw/2016W/thalia-restaurant.pdf"
}

然后提取它的最简单方法可能是使用正则表达式。虽然这通常一个坏主意,但在这里您正在寻找一个非常具体的东西 - 一个文件,用“引号”包裹,以 .pdf 结尾。以下代码将找到并提取 URL:

import re
from urllib import urlopen

html = urlopen("http://www.nycgo.com/venues/thalia-restaurant#menu")
html_doc = html.read()

match = re.search(b'\"(.*?\.pdf)\"', html_doc)
pdf_url = "http://www.nycgo.com" + match.group(1).decode('utf8')

现在 pdf_url 是:

u'http://www.nycgo.com/assets/files/programs/rw/2016W/thalia-restaurant.pdf'

但是,从 PDF 中提取文本有点棘手。您可以先下载文件:

from urllib import urlretrieve
urlretrieve(pdf_url, "download.pdf")

然后使用函数 in this answer to another question 提取文本:

text = convert_pdf_to_txt("download.pdf")
print(text)

返回:

NEW YOUR CITY 
RESTAURANT WEEK

WINTER 2016

MONDAY - FRIDAY
828 Eighth Avenue
New York City, 10019

Tel: 212.399.4444

www.restaurantthalia.com

LUNCH $25
FIRST COURSE
CREAMY POLENTA
fricassee of truffle mushrooms

...

关于Python 从 URL 抓取 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34819638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com