社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Selenium python BeautifulSoup卡在当前页面

sh1515 • 4 年前 • 118 次点击  

我正在尝试用漂亮的汤刮一个公共的facebook组,我正在使用移动网站,因为那里没有javascript。所以这个脚本应该从“more”关键字中获取链接,从p标记中获取文本,但它只是从当前页面的p标记中获取文本。有人能给我指出这个问题吗?我对python和这段代码中的所有内容都不熟悉。

   from selenium import webdriver
   from selenium.webdriver.common.keys import Keys
   from selenium.common.exceptions import NoSuchElementException
   from bs4 import BeautifulSoup
   import requests
   browser = webdriver.Firefox()
   browser.get('https://mobile.facebook.com/groups/22012931789?refid=27')
   for elem in browser.find_elements_by_link_text('More'):
      page = requests.get(elem.get_attribute("href"))
      soup=BeautifulSoup(page.content,'html.parser')
      print(soup.find_all('p')[0].get_text()) 
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/37915
 
118 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Danielle M.
Reply   •   1 楼
Danielle M.    5 年前

查看脚本实际上在做什么总是很有用的,一种快速的方法是在过程中的某些步骤打印结果。

例如,使用代码:

for elem in browser.find_elements_by_link_text('More'):
    print("elem's href attribute: {}".format(elem.get_attribute("href")))

你会注意到第一个是空白的。在尝试获取获取请求之前,我们应该对此进行测试:

for elem in browser.find_elements_by_link_text('More'):
    if elem.get_attribute("href"):
        print("Trying to get {}".format(elem.get_attribute("href")))
        page = requests.get(elem.get_attribute("href"))
        soup=BeautifulSoup(page.content,'html.parser')
        print(soup.find_all('p')[0].get_text())

注意一个空的 elem.get_attribute("href") 返回空的Unicode字符串, u'' -但蟒蛇认为空字符串是假的,这就是为什么 if 作品。

在我的机器上工作很好。希望有帮助!