【问题标题】:Issue with searching for text within a returned string在返回的字符串中搜索文本的问题
【发布时间】:2014-12-21 01:50:40
【问题描述】:

我已经编写了返回这个的代码:

<div id="IncidentDetailContainer"><p>The Fire Service received a call reporting a car on fire at    the above location. One fire appliance from Ashburton attended.</p><p>Fire crews confirmed one car   well alight and severley damaged by fire. The vehicle was extinguished by fire crews using two   breathing apparatus wearers and one hose reel jet. The cause of the fire is still under investigation   by the Fire Service and Police.</p><p> </p><p> </p></div>

我想搜索它并找到“Ashburton”部分,但到目前为止,无论我使用什么,我都没有返回或 []。

我的问题是:这是一个可以搜索的普通字符串(我做错了什么)还是因为我从网页源代码中得到它,我无法以正常方式搜索它?

应该很简单,我知道,但我还是没有!

from bs4 import BeautifulSoup
from urllib import request
import sys, traceback

webpage = request.urlopen("http://www.dsfire.gov.uk/News/Newsdesk/IncidentsPast7days.cfm?siteCategoryId=3&T1ID=26&T2ID=35")
soup = BeautifulSoup(webpage)
incidents = soup.find(id="CollapsiblePanel1")
Links = []
for line in incidents.find_all('a'):
    Links.append("http://www.dsfire.gov.uk/News/Newsdesk/"+line.get('href'))
n = 0
e = len(Links)
if e == n:
   print("No Incidents Found Please Try Later")
   sys.exit(0)
while n < e:
    webpage = request.urlopen(Links[n])
    soup = BeautifulSoup(webpage)
    station =  soup.find(id="IncidentDetailContainer")
    #search string
    print(soup.body.findAll(text='Ashburton'))
    n=n+1

仅供参考,如果网页今天没有任何事件,它不会搜索任何内容(显然)这就是我包含返回的字符串的原因,所以如果你运行它却什么也没得到,这就是原因。

【问题讨论】:

  • 您要查找包含“Ashburton”或标签的文本吗?
  • 我得到了包含名称的标签,但我想在标签内搜索,因为名称会改变,我想最终搜索不同的名称

标签: string search beautifulsoup webpage


【解决方案1】:

text= 中提供一个模式。从您提供的html 中,如果您想找到其中包含“Ashburton”的tag,您可以使用这样的东西,

soup.find_all('p', text=re.compile(r'Ashburton'))

这样只能获取文本,

soup.find_all(text=re.compile(r'Ashburton'))

【讨论】:

  • 非常感谢,效果更好!我最终将用从列表中选择的名称替换该名称,因此不是“Ashburton”,而是类似于 lstName.selected 的名称,因此如果用户想要搜索不同的电台,他们可以!非常感谢,这是我完成的项目中最好的部分! ? 到家我会检查的!
  • 刚刚检查并确定它确实有效!非常感谢你!!只是一个简单的问题,是否可以将“Ashburton”替换为包含 Ashburton 的变量?即 Station = "Ashburton" soup.find_all(text=re.compile(rStation)) 会将问题标记为已回答。 @salmanwahed
  • 是的,你可以这样做:soup.find_all('p', text=re.compile(r'{}'.format(Station)))
猜你喜欢
  • 2018-06-24
  • 2013-12-13
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-09
相关资源
最近更新 更多