无法使用漂亮的汤来为此特定页面检索href

时间:2019-02-13 05:21:46

标签: python html web-scraping beautifulsoup href

以下是我的代码:

transition.startAnim

我要定位以下href:

0

我想在上面提取href,但是我得到# -*- coding: ascii -*- # import libraries from bs4 import BeautifulSoup import urllib2 import re def gethyperLinks(url): html_page = urllib2.urlopen(url) soup = BeautifulSoup(html_page, "html.parser") hyperlinks = [] for link in soup.findAll('div', attrs={'class': 'ess-product-desc'}): hyperlinks.append(link.get('href')) return hyperlinks print( gethyperLinks("http://biggestbook.com/ui/catalog.html#/search?cr=1&rs=12&st=BM&category=1") ) 作为最终答案。我在做什么错了?

2 个答案:

答案 0 :(得分:1)

该页面的值需要JavaScript才能运行。如果您检查响应(至少在请求中),那应该很清楚。我展示了一个使用硒的示例,以便javascript有时间运行。当您在抓取会话期间从导航到的页面返回数据时,可以将其转换为使用函数。 从硒导入webdriver 从selenium.webdriver.support.ui导入WebDriverWait 从selenium.webdriver.support导入EC的预期条件 来自selenium.webdriver.common.by导入方式 chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('-headless') 驱动程序= webdriver.Chrome(chrome_options = chrome_options) driver.get(“ http://biggestbook.com/ui/catalog.html#/search?cr=1&rs=12&st=BM&category=1”) 链接= WebDriverWait(驱动程序,10)。直到(EC.presence_of_all_elements_located((由CSS.SELECTOR,“ .ess-product-brand + [href]”))) 结果= [link.get_attribute('href')用于链接中的链接] 打印(结果) 有一个带有查询字符串参数的API,该API以json格式返回数据。您必须传递引荐来源网址和令牌。如果您能够获取令牌或在会话中传递令牌(并且令牌仍然有效),并且可以解密查询字符串参数,那么这可能是基于请求的方法的方法。不确定urllib。 https://api.essendant.com/digital/digitalservices/search/v1/search?cr=1&fc=1&listKey=I:D2F9CC81D2919D8712B61A3176A518622A2764B16287CA6576B9CF0C9B5&listKey=I:A81AAA8BD639792D923386BBACAC32AC535673EAF

答案 1 :(得分:0)

也许,您应该使用“ html5lib”而不是“ html.parser”,例如:

from bs4 import BeautifulSoup
html="""
<div 
    class="ess-product-desc" ng-hide="currentView == 'detail' `&amp;&amp; deviceType=='mobile'" 
    ui-sref="detail({itemId: 'BWK6400', uom: 'CT', cm_sp:'', merchPreference:''})" 
    href="#/itemDetail?`itemId=BWK6400&amp;uom=CT" aria-hidden="false">
        <span>Center-Pull Hand Towels, 2-Ply, Perforated, 7 7/8 x 10, White, 600/RL, 6 RL/CT</span>
</div>
"""
soup = BeautifulSoup(html,"html5lib")
links = soup.findAll('div', attrs={'class': 'ess-product-desc'})
links[0].get("href")

您将得到:

'#/itemDetail?`itemId=BWK6400&uom=CT'