从<class'bs4.element.Tag'>

时间:2019-06-15 15:17:49

标签: python beautifulsoup

当我打印元素时,我正在从类型类bs4.element.Tag中提取数据。 我只想提取“ data-keyword =“部分,所以基本上只提取了关键字,但是没有成功。

除了阅读以前的文章,这是我已经尝试过的方法:

import time
from bs4 import BeautifulSoup
from selenium import webdriver

browser = webdriver.Chrome('chromedriver.exe')
keyList = ['a','b','c']
mainUrl = "https://www.amazon.com/"
browser.get(mainUrl)
searchInput = browser.find_element_by_xpath('//input[@id="twotabsearchtextbox"]')
searchInput.clear()
for keyChar in keyList:
        time.sleep(2)
        searchSoup = BeautifulSoup(browser.page_source, "html.parser")
        searchResult = searchSoup.find_all('div', attrs={'id':'suggestions-template'})
        results = searchResult[0].find_all('div', attrs={'class':'s-suggestion'})
        time.sleep(1)
        for x in results:
            print(x)
            print(type(x))
            narrow_down = x.find_all('div', attrs={'data-keyword:'})
            print(narrow_down)

这就是我得到的:

<div class="s-suggestion" data-alias="aps" data-crid="2D6LIH2IP11XU" data-isfb="false" data-issc="false" data-keyword="amazon gift cards" data-nid="" data-reftag="nb_sb_ss_i_1_1" data-store="" data-type="a9" id="issDiv0"><span class="s-heavy"></span>a<span class="s-heavy">mazon gift cards </span></div>
<class 'bs4.element.Tag'>
[]

我如何只打印data-keyword =?

1 个答案:

答案 0 :(得分:0)

解决方案是将类型更改为str。 更改类型后,从中提取子字符串。     new_str = str(x)