【发布时间】:2021-05-23 20:11:31
【问题描述】:
我正在尝试从 url 获取内容并使用 BeautyfulSoup 解析响应。
加载此 url 时,它会检索我最喜欢的监视列表项目,问题是当站点加载时,它需要几秒钟才能在表格中显示数据,所以当我运行 urlopen(my_url) 时,响应没有表格,因此我的解析方法失败了。
我正在努力保持简单,因为我正在学习语言,所以我想使用我已经在我的代码中设置的工具,所以根据我所拥有的,我想知道是否有办法等待,或检查内容何时可供我获取数据(表格内容)。
这是我的代码:
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as ureq
from urllib.error import URLError, HTTPError
URL = 'url route goes here' # In compliance to SO rules I've removed the website path
def get_dom_from_url():
try:
u_client = ureq(URL)
html = u_client.read()
u_client.close()
except HTTPError as e:
print(f'There has been an HTTP ERROR: {e.code}')
except URLError as e:
print(f'There has been a problem reaching the URL. ERROR: {e.code}')
finally:
print('''
DOM loaded!
''')
return html
dom = soup(get_dom_from_url(), 'html.parser')
# Crawl the dom object and get the table thead element
col_names = [col.text for col in dom.table.thead.find_all('th')]
col_names = col_names[1:-2]
col_names
这是错误信息:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-102-625de133b2e2> in <module>
----> 1 col_names = [col.text for col in dom.table.thead.find_all('th')]
2 col_names = col_names[1:-2]
3 col_names
AttributeError: 'NoneType' object has no attribute 'thead'
当我在没有路由的情况下加载 url 时,上面的代码有效,但我需要它,因为我需要为我正在处理的 ETL 管道存储相同的数据。
如果仅使用 urllib 无法实现此目的,我想听听您的建议。
【问题讨论】:
-
你能像
get_dom_from_url(URL)一样在该函数中传递URL作为参数,然后像dom = soup(get_dom_from_url(URL), 'html.parser')一样声明dom -
是的,但我最终遇到了同样的情况,该网站需要几秒钟来获取关注列表并显示数据
-
此外,依赖于随机外部网站的问题通常被认为没有minimal reproducible example。
-
@user202729 注意,谢谢。
-
@user202729 我理解,但是像这样涉及通过 javascript 动态加载的数据抓取的案例,不容易变成独立的可重现示例。原则上不要太严格。
标签: python beautifulsoup urllib