如何使用 find_all() 提取所需的元素
How to extract the required element using find_all()
我正在尝试提取亚马逊页面中的作者姓名。问题是,有太多具有相同 class 的标签,并且没有其他属性来标识确切的元素。现在我想提取作者姓名。它出现在第二个 span 标签中。
<div class="a-row a-spacing-none">
<span class="a-size-small a-color-secondary">by </span>
<span class="a-size-small a-color-secondary"><a class="a-link-normal a-text-normal" href="/Arthur-Conan-Doyle/e/B000AQ43GQ/ref=sr_ntt_srch_lnk_2?qid=1510823399&sr=8-2">Arthur Conan Doyle</a></span></div>
尽我们所能,两个 span 标签都有相同的 class。我想要第二个 span tag.And 结束,所有块中都不存在 a 标签。所以我必须只使用 span 标签来提取作者姓名。我如何获得作者姓名?
我正在使用 BeautifulSoup 和 selenium.My 代码是:
soup=BeautifulSoup(self.driver.page_source,"html.parser")
titles=soup.find_all("h2",{"class":"a-size-medium s-inline s-access-title a-text-normal"})
authors=soup.find_all("span",{"class":"a-size-small a-color-secondary"})
for value in range(len(titles)):
d={}
d["Title"]=titles[value].text
d["Author"]=authors[value+2].text
title.append(d)
为 "span" 找到上述 "div" 元素。然后提取 div tag.As 你观察的整个文本,每个代码块中都会有一个 "by" 子字符串。用它来拆分文本,复制到d["Author"]部分。如果 "by" 不存在,请在使用 if 条件将其复制到字典之前进行检查。如果你直接复制,那么你可能会得到 Array out of Bound 异常。所以使用 if.
代码如下:
temp = authors[value].text
temp1 = temp.split("by")
#print(temp[1])
if temp1[0]!=temp:
d["Author"] = temp1[1]
else:
d["Author"] = "None"
我正在尝试提取亚马逊页面中的作者姓名。问题是,有太多具有相同 class 的标签,并且没有其他属性来标识确切的元素。现在我想提取作者姓名。它出现在第二个 span 标签中。
<div class="a-row a-spacing-none">
<span class="a-size-small a-color-secondary">by </span>
<span class="a-size-small a-color-secondary"><a class="a-link-normal a-text-normal" href="/Arthur-Conan-Doyle/e/B000AQ43GQ/ref=sr_ntt_srch_lnk_2?qid=1510823399&sr=8-2">Arthur Conan Doyle</a></span></div>
尽我们所能,两个 span 标签都有相同的 class。我想要第二个 span tag.And 结束,所有块中都不存在 a 标签。所以我必须只使用 span 标签来提取作者姓名。我如何获得作者姓名?
我正在使用 BeautifulSoup 和 selenium.My 代码是:
soup=BeautifulSoup(self.driver.page_source,"html.parser")
titles=soup.find_all("h2",{"class":"a-size-medium s-inline s-access-title a-text-normal"})
authors=soup.find_all("span",{"class":"a-size-small a-color-secondary"})
for value in range(len(titles)):
d={}
d["Title"]=titles[value].text
d["Author"]=authors[value+2].text
title.append(d)
为 "span" 找到上述 "div" 元素。然后提取 div tag.As 你观察的整个文本,每个代码块中都会有一个 "by" 子字符串。用它来拆分文本,复制到d["Author"]部分。如果 "by" 不存在,请在使用 if 条件将其复制到字典之前进行检查。如果你直接复制,那么你可能会得到 Array out of Bound 异常。所以使用 if.
代码如下:
temp = authors[value].text
temp1 = temp.split("by")
#print(temp[1])
if temp1[0]!=temp:
d["Author"] = temp1[1]
else:
d["Author"] = "None"