

嗨,我想从em标签中获取文本(数字18),如上图所示。当我运行我的代码时,它不工作,只给我一个空列表。有谁可以帮我?谢谢~
这是我的代码。
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = 'https://blog.naver.com/kwoohyun761/221945923725'
html = urlopen(url)
soup = BeautifulSoup(html, 'lxml')
likes = soup.find_all('em', class_='u_cnt _count')
print(likes)发布于 2020-10-06 17:57:33
当您禁用javascript时,您将看到like计数是动态加载的,因此您必须使用呈现网站的服务,然后才能解析内容。
您可以使用一个接口:https://www.scraperapi.com/
或者运行您自己的,例如:https://github.com/scrapinghub/splash
编辑:
首先,我没有注意到你错误地使用了urlopen,正确的方式在这里描述:https://docs.python.org/3/howto/urllib2.html。假设您使用的是python3,从print语句来判断似乎就是这种情况。
此外,再看一遍这个问题,它就有点复杂了。当你查看页面的源代码时,它实际上加载了一个iframe,在这个iframe中你有实际的内容:点击ctrl +u来查看原始url的源代码,因为侧边似乎阻止了浏览器的上下文菜单。
因此,为了实现爬行目标,您必须首先抓取初始页面,然后抓取您感兴趣的页面:
from urllib.request import urlopen
from bs4 import BeautifulSoup
# original url
url = "https://blog.naver.com/kwoohyun761/221945923725"
with urlopen(url) as response:
html = response.read()
soup = BeautifulSoup(html, 'lxml')
iframe = soup.find('iframe')
# iframe grabbed, construct real url
print(iframe['src'])
real_url = "https://blog.naver.com" + iframe['src']
# do your crawling
with urlopen(real_url) as response:
html = response.read()
soup = BeautifulSoup(html, 'lxml')
likes = soup.find_all('em', class_='u_cnt _count')
print(likes)您可以通过分析原始url和iframe中的URL来避免一次往返。乍一看,似乎iframe url可以从原始url构建。
你仍然需要一个渲染版本的iframe url来获取你想要的值。
我不知道这个网站是关于什么的,但他们似乎不想被爬行,也许你会尊重这一点。
https://stackoverflow.com/questions/64223359
复制相似问题