如何webscrape嵌套的div和ol类

时间:2019-06-22 23:05:16

标签: python html web-scraping twitter beautifulsoup

我正在尝试刮擦this webpage

我希望从“照片流容器”中下载一些照片,但没有成功。下面是我目前正在使用的代码块。

查找所有以'Adaptive'开头的span类 作为示例类,将是“ AdaptiveStreamGridImage网格推特has-cards has-content启用了清除第一行hoverZoomLink”

有什么建议吗?

d = requests.get('https://twitter.com/search?f=images&vertical=news&q=Iran').text
soup = BeautifulSoup(d, 'html.parser')

spans = soup.findAll("span", {"class": lambda x: x and x.startswith('Adaptive')})
print(spans)

打印“跨度”时我收到一个空列表

[]

1 个答案:

答案 0 :(得分:0)

所需的内容很可能已被JS脚本隐藏。我们的request库是一个不用担心那些JS脚本的东西,它可以获取在浏览器的JSless模式下对您可见的内容。 可以在selenium库的帮助下解决此问题。它允许您加载网页及其内容,就像您使用的任何其他浏览器一样。 因此,使用Selenium有一些解决方法:

from selenium import webdriver
#Initiate your browser
browser = webdriver.Firefox() 
#It's Firefox in my case, you can have Chrome or Safari or Opera, depending upon the webdriver you have installed in your system
url = 'https://twitter.com/search?f=images&vertical=news&q=Iran'
#Fetch the URL in the 'browser'
browser.get(url)
#Get the page source of the browser
soup = BeautifulSoup(browser.page_source, 'html.parser')
#This page source is pretty similar to the one you see in your inspect element
browser.close() #'browser' has finished it's work, so 'close()' it
#Now apply whatever function you wish to on the webpage
spans = soup.findAll("span", {"class": lambda x: x and x.startswith('Adaptive')})
print(spans)