我正在尝试从此链接中提取特定文本:
http://www1.folha.uol.com.br/fsp/mercado/index-20121030.shtml
我写了这个函数来查找和提取一段文字:
def manchete_11112011_30102012(b):
soup = make_soup(b)
data = [span.string for span in soup.find("font")]
noticias = [b.text for b in soup.findAll("a")]
return {"noticias": noticias,
"data": data}
行。我的问题在于“数据”行。当它运行时它什么都不返回。当我写“span.string”时,它会返回“[none]”,当我写“span.text”时,它会返回 “[U”]“
这是我正在寻找的HTML代码。我需要<span id="spanLongDate">
中的文字内容:
<<td width="430" align="right"><font size="1"><span id="spanLongDate">São Paulo, terça-feira, 30 de outubro de 2012</span></font><img src="images/mercado.gif" hspace="10" alt="Mercado"></td>
有没有其他方法可以提取文字?我的意思是,我写错了代码,还是文本格式不兼容? “[你”]的意思是什么?
答案 0 :(得分:0)
要查找id = spanLongDate
,请使用以下片段
//get the span you are looking for
span = soup.find("span", attrs = {"id":"spanLongDate"})
//get the text out of the span
data = span.get_text()
请注意,如果您必须使用.find_all
ETA:
根据您的以下评论我去看了一下页面来源,甚至在我的机器上运行它。这是一个功能,允许您转储beautifulsoup看到的内容。这很有用,因为有时候在浏览器中查看源代码时看不到的内容。
def dumpPage():
url = "http://www1.folha.uol.com.br/fsp/mercado/index-20121030.shtml"
print("url is: " + url)
page=urllib.request.urlopen(url)
soup = BeautifulSoup(page.read())
print("read soup")
print(soup)
当我打印出来并搜索&#34; spanLongDate&#34;我得到了以下感兴趣的片段。
<td align="right" width="430"><font size="1"><span id="spanLongDate"></span></font><img alt="Mercado" hspace="10" src="images/mercado.gif"/></td>
其中没有圣保罗文本。然后,我在Chrome浏览器中点击F12查找原始来源,spanLongDate
<div>
中也没有文字。
也许页面已更新?
答案 1 :(得分:0)
如果你只想要日期,你应该在其他地方寻找它。如果您丢弃汤然后搜索2012,您将在许多地方看到它。使用以下代码很容易将其从标题中删除。
url = "http://www1.folha.uol.com.br/fsp/mercado/index-20121030.shtml"
page=urllib.request.urlopen(url)
soup = BeautifulSoup(page.read())
theDateTag = soup.find("title")
theDateString = theDateTag.get_text()
print(theDateString)