Web Scraping Python(BeautifulSoup,Requests)

Web Scraping Python(BeautifulSoup,Requests)

问题描述:

我正在学习使用python进行网页抓取,但无法获得所需的结果。下面是我的代码和输出Web Scraping Python(BeautifulSoup,Requests)

代码

import bs4,requests 
url = "https://twitter.com/24x7chess" 
r = requests.get(url) 
soup = bs4.BeautifulSoup(r.text,"html.parser") 
soup.find_all("span",{"class":"account-group-inner"}) 
[] 

这里是我试图刮

https://i.stack.imgur.com/tHo5S.png

我一直得到一个空数组。请帮忙。

+0

你为什么不使用Twitter官方的API?网络报废对于Twitter来说并不理想。 – Saharsh

+0

其实我刚刚开始这个,这就是为什么我要走更多的全面路径,而不是只关注Twitter API –

试试这个。它会给你你可能寻找的物品。 SeleniumBeautifulSoup很容易处理。我已经这样写了。这里是。

from bs4 import BeautifulSoup 
from selenium import webdriver 

driver = webdriver.Chrome() 

driver.get("https://twitter.com/24x7chess") 
soup = BeautifulSoup(driver.page_source,"lxml") 
driver.quit() 
for title in soup.select("#page-container"): 
    name = title.select(".ProfileHeaderCard-nameLink")[0].text.strip() 
    location = title.select(".ProfileHeaderCard-locationText")[0].text.strip() 
    tweets = title.select(".ProfileNav-value")[0].text.strip() 
    following = title.select(".ProfileNav-value")[1].text.strip() 
    followers = title.select(".ProfileNav-value")[2].text.strip() 
    likes = title.select(".ProfileNav-value")[3].text.strip() 
    print(name,location,tweets,following,followers,likes) 

输出:

akul chhillar New Delhi, India 214 44 17 5 
+0

非常感谢。我已经开始使用Selenium了,它的功能很神奇 –

+0

如果它有效,请务必将其标记为答案。谢谢。 – SIM

+0

我也可以在这里使用find_all方法而不是使用select? –

像Twitter这样的网站会动态加载内容,这有时候取决于您使用的浏览器等。由于动态加载,网页中可能会有一些元素被延迟加载,这意味着DOM会动态膨胀,取决于用户的操作,您在浏览器中检查的标记Inspect元素,会检查完全动态膨胀的HTML,但是您使用请求获得的响应,HTML膨胀,或者是一个简单的DOM等待动态加载元素用户在从请求模块提取时的行为是None。

我建议你使用硒webdriver刮动态JavaScript网页。

+0

嗨。感谢您抽出时间。我注意到了一些我只能查看视图源中的数据而不是我在网站上检查的数据的东西。你可以看看这个吗? –

+0

@akulchhillar与请求您只能获取静态DOM,对于需要使用['selenium'](http://selenium-python.readthedocs.io/)模块 – ZdaR

+0

谢谢。我最近学习硒。顺便说一句,如果我使用urllib来删除动态网站? –