首页 文章

Beautiful Soup - 连字符关键字,Error :: keyword不能是表达式

提问于
浏览
0

我正在使用Selenium然后使用Beautiful Soup来尝试抓取网页,该页面使用JavaScript来加载某些内容 . Selenium给了我简单的html,我已经检查了这个,使用print并发现它确实包含了我试图刮擦的部分 . 但我的问题是美丽的汤 .

我想找到div标签

class="comment-detail"

我试过用了

comments = soup.find_all("div", class_="comment-detail")

但是这会返回空,可能是因为实际的div标签也包含在其中

data-selenium="reviews-comments"

html中的确切标记是

<div data-selenium="reviews-comments" class="comment-detail">

所以我尝试了以下,

comments = soup.find_all("div", data-selenium="reviews-comments", class_="comment-detail")

但是这给出了错误

SyntaxError: keyword can't be an expression

以来

data-selenium

当它实际上只是一个带连字符的单词时,就像一个减法运算 . 我试过把它用引号括起来,但这没有用 .

我也试过了

dct = {
    'div': '',
    'data-selenium': 'reviews-comments',
    'class': 'comment-detail'

}
comments = soup.find_all(**dct)

len(comments)

返回零,即注释为空 .

为了清楚起见我的汤我有代码

from selenium import webdriver  
from selenium.common.exceptions import NoSuchElementException  
from selenium.webdriver.common.keys import Keys  
from bs4 import BeautifulSoup

browser = webdriver.Firefox()  
browser.get('http://www.agoda.com/the-coast-resort-koh-phangan/hotel/koh-phangan-th.html/')  
html_source = browser.page_source  
browser.quit()

soup = BeautifulSoup(html_source,'html.parser')

有什么想法在这里继续吗?

1 回答

  • 0

    问题源于URL,您在末尾有一个额外的正斜杠,它返回404页面而不是您真正想要的页面 . 只需删除它,您的代码就可以了 .

    这是我以前使用的代码:

    from selenium import webdriver  
    from selenium.common.exceptions import NoSuchElementException  
    from selenium.webdriver.common.keys import Keys  
    from bs4 import BeautifulSoup
    
    browser = webdriver.Firefox()  
    browser.get('http://www.agoda.com/the-coast-resort-koh-phangan/hotel/koh-phangan-th.html')  
    html_source = browser.page_source  
    browser.quit()
    
    soup = BeautifulSoup(html_source, 'html.parser')
    
    comments = soup.find_all("div", class_="comment-detail")
    
    print(comments)
    

相关问题