使用Selenium进行Web爬网

时间:2019-02-25 13:29:15

标签: python html selenium web-scraping beautifulsoup

我正在尝试从Youtube提取一些数据,但是我在捕捉文本方面很挣扎,这是我的代码:

username = "unboxtherapy"
driver = webdriver.Chrome('C:/Users/Chrome Web Driver/chromedriver.exe')
api_url = "https://www.youtube.com/user/"+username+"/about"
driver.get(api_url)
html = driver.find_element_by_tag_name('html')
soup=bs(html.text,'html.parser')
text=str(soup)

在上面的示例中,我试图捕获页面上显示的描述。

soup

返回页面上的所有文本,即我想要的描述+大量我不想要的其他东西。

text

返回以下所有文本:

  

“ GB \ n登录\ n拆箱治疗\ n13,802,667   订阅者\ nJOIN \ nSUBSCRIBE \ nTwitter \ nHOME \ nVIDEOS \ nPLAYLISTS \ n社区\ nCHANNELS \ nABOUT \ n描述\ n   产品变得裸露。\ n \ n您会在这里找到各种视频   展示地球上最酷的产品。从最新的   智能手机,提供您从未知道的令人惊讶的小工具和技术   存在。全部都在Unbox Therapy上。\ n \ n企业/专业人士   仅限查询-unboxtherapy.com [n]业务(请不要使用   YouTube收件箱)\ nLinks \ nTwitter Facebook Instagram官方   网站\ n统计信息\ n2010年12月21日加入\ n2,698,921,226观看次数\ nOTHER COOL   频道。\ n稍后再来\ n订阅\ n马克斯·布朗利\ n订阅\ n乔纳森   莫里森\ n订阅\ n奥斯丁   埃文斯\ nSUBSCRIBE \ n底特律BORG \ nSUBSCRIBE \ nLooneyTek \ nSUBSCRIBE \ n士兵   最了解\ nSUBSCRIBE \ nUrAvgConsumer \ nSUBSCRIBE \ n相关   频道\ nLinus Tech   提示\ nSUBSCRIBE \ nJerryRigEverything \ nSUBSCRIBE \ nMrwhotheboss \ nSUBSCRIBE \ nTechSmartt \ nSUBSCRIBE”

有没有办法仅捕获描述?可能吗?

在此先感谢您能帮助我的人。

最良好的祝愿

2 个答案:

答案 0 :(得分:1)

尝试以下代码。让我知道它是否有效。

<plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <mainClass>com.places.Main</mainClass>
        </configuration>

        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
       </executions>

</plugin>

输出:

import bs4 as bs
import re
username = "unboxtherapy"
driver = webdriver.Chrome('C:/Users/Chrome Web Driver/chromedriver.exe')
api_url = "https://www.youtube.com/user/"+username+"/about"
driver.get(api_url)
html = driver.page_source
soup=bs.BeautifulSoup(html,'html.parser')
findtext=soup.find_all('yt-formatted-string',id=re.compile("description"))
for txt in findtext:
    print(txt.text)

答案 1 :(得分:1)

仅使用硒即可完成简单的解析。

driver.get(api_url)
description = drvier.find_element_by_id('description')
print(description.text)

(如果您使用chrome并了解检查的话)
知道标签名称,ID或属性值:

  1. 只需右键单击描述文本(您要查找元素)
  2. 像这样选择“检查”:

like this

然后您可以像这样检查值:

like this

  • 粉红色文本:标签名称
  • “#”和橙色文字:id
  • '。 %蓝色文本:属性值

现在使用驱动程序方法

driver.find_by_elemeent_by_tag_name()  
driver.find_by_elements_by_tag_name()  
driver.find_by_element_id()  
driver.find_by_elements_id()  
driver.find_by_element_class_name()  
driver.find_by_elements_class_name()  
相关问题