【问题标题】:Beautiful Soup - hyphenated keyword, Error :: keyword can't be an expressionBeautiful Soup - 连字符关键字,错误 :: 关键字不能是表达式
【发布时间】:2016-09-26 12:20:06
【问题描述】:

我使用 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)

返回零,即 cmets 为空。

为了清楚起见,我有代码

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')

有什么想法可以在这里进行吗?

【问题讨论】:

    标签: python beautifulsoup keyword


    【解决方案1】:

    问题源于 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)
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2020-02-10
    • 2012-07-22
    • 2013-06-04
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    相关资源
    最近更新 更多