我正在尝试从 HTML 内的表格中抓取代码。由于它在表中,它们都共享相同的标签,因此我无法找到另一种方法来隔离该字符串。我使用的方式是喜怒无常的。
表格元素:
<table class="factsheet-table table-no-border spacer-bottom">
…
<tbody>
…(to the required line)
<tr class="table-alt">
<th class="align-left">
ISIN:
</th>
<td class="align-left">
XS0105244585
</td>
</tr>
quote_page = 'https://www.hl.co.uk/shares/shares-search-results/t/tesco-6-2029'
page = urlopen(quote_page)
soup = BeautifulSoup(page, 'html.parser')
# Get Bond code
search = re.compile('ISIN:')
bond_code = soup.find(text=search).parent.find_next('td').contents[0]
code = bond_code.strip()
我只想获取代码,但我能想到的隔离它的唯一方法是获取“ISIN:”之后的下一行代码
我通常会收到“AttributeError: 'NoneType' object has no attribute (parent/find_next…)”的变体
最佳答案
你的代码看起来不错,它也对我有用。 由于没有其他任何东西可以锚定搜索,我认为使用文本选择器是可以接受的。
但是,您正在抓取的网站有时不会响应页面,而是显示如下错误消息:
<html><head>
<H1>Request Rejected</H1>
</head>
<body><P>The requested URL was rejected.</P>
<P>Please contact the Hargreaves Lansdown internet support team on 0116 800 8000 quoting reference: 1112223334445556667</P>
</body>
</html>
在这种情况下,它无法找到您的文本正则表达式,并且会失败。
您可以通过简单地重试整个 block 来解决此问题:
from bs4 import BeautifulSoup
from urllib2 import urlopen
import re
from time import sleep
# retry 10 times
for attempt in range(10):
quote_page = 'https://www.hl.co.uk/shares/shares-search-results/t/tesco-6-2029'
page = urlopen(quote_page).read()
try:
soup = BeautifulSoup(page, 'html.parser')
search = re.compile('ISIN:')
bond_code = soup.find(text=search)
bond_code = bond_code.parent.find_next('td').contents[0]
code = bond_code.strip()
print("Found code:")
print(code)
except Exception as e:
# log the error or simply pass
print(e)
print("Page was:")
print(page)
sleep(2) # wait 2 seconds before retrying
else:
break
else:
# we failed all the attempts - deal with the consequences.
print("Failed 10 times to get ISIN")
您还可以使用 python 库来重试以使您的代码看起来更好,例如:
关于python - 如何抓取 HTML 的下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57112674/