使用BeautifulSoup进行网络抓取:在标签外找到文本

时间:2018-09-18 17:13:50

标签: python beautifulsoup

我正在尝试通过返回genlib的某些搜索结果的书名来玩BeautifulSoup:

from bs4 import BeautifulSoup
import requests
import re

url = "http://gen.lib.rus.ec/search.php?req=physics&lg_topic=libgen&open=0&view=simple&res=25&phrase=1&column=def"
soup = BeautifulSoup(requests.get(url).text, 'lxml')

for html in soup.find_all('tr', {'valign': 'top', 'bgcolor':'#C6DEFF'}):
    print(html.find('a', {'href': re.compile("book/index.php\?md5=.")}).text)

相关的HTML:

<a href="book/index.php?md5=AAC0058748685BAEB782D1A156A2ED25" id="28" title="">
 Physics of life
 <br/>
 <font color="green" face="Times">
  <i>
   0444527982, 9780444527981, 9780080554648
  </i>
 </font>
</a>
<a href="book/index.php?md5=C892C74AEAC46715475EF5334302D751" id="48" title="">
 Physics and Chemistry Basis of Biotechnology
 <br/>
 <font color="green" face="Times">
  <i>
   9780306468919, 0306468913
  </i>
 </font>
</a>

一切正常,除了输出中包含一些不需要的ISBN代码:

"""
Physics of life 0444527982, 9780444527981, 9780080554648

Physics and Chemistry Basis of Biotechnology 9780306468919, 0306468913

Lectures On Statistical Physics And Protein Folding [illustrated edition] 9812561439, 9789812561435, 9789812569387, 9812561501
...
"""

我想摆脱数字,但是书名和数字都位于<a></a>标记内,而数字更位于<i></i>标记内。在我看来,我可以通过在末尾加上“ .i.text”来提取ISBN,但是我怎么只提取书名呢?

3 个答案:

答案 0 :(得分:0)

我不确定是否有一种优美的方法可以通过beautifulsoup提取书名。

一个简单的解决方法是提取ISBN,然后使用replace函数将ISBN替换为空字符串。然后使用剥离功能清理所有空白。

titleString.replace(isbnString, "").strip()

替换: https://www.tutorialspoint.com/python/string_replace.htm

条带: https://www.tutorialspoint.com/python/string_strip.htm

答案 1 :(得分:0)

for html in soup.find_all('tr', {'valign': 'top', 'bgcolor':'#C6DEFF'}):
    print(html.find('a', {'href': re.compile("book/index.php\?md5=.")}).next)

next返回汤中的下一个标签文本。

答案 2 :(得分:0)

使用find_next

for html in soup.find_all('tr', {'valign': 'top', 'bgcolor':'#C6DEFF'}):
    print(html.find('a', {'href': re.compile("book/index.php\?md5=.")}).find_next(text = True))