我有一个奇怪的问题。我正在使用 python 使用 beautiful soup 来抓取页面。我需要的一个值位于 tr 元数据中,我可以使用以下命令将其打印到屏幕上:
meta = tr.findNext('td', {'class':'field1'})
attr_dict = meta.a.attrs
print(attr_dict)
这会产生:
{'href': '/client/displayEmail.asp?rid=1318441&cid=12339',
'rel': ['gb_page_center[940,', '600]'],
'title': 'ID: manualavenue100daily120141127073104:EG_CO_NEWS_1/08-14-14_yahoo\rLooking for schools? Get free information today.\rFrom: degree@newsconsul.com\rDate: 11/27/2014 7:33:34 AM'}
我想提取以下信息:EG_CO_NEWS_1/08-14-14_yahoo,但似乎无法获取。
目前我正在这样做:
campaign_raw = str(attr_dict['title'][:80])
产生:
'Lookianualavenue100daily120141127073104:EG_CO_NEWS_1/08-14-14_yahoo'
主题和模板名称以意外的顺序奇怪地串联。
我尝试将字符串拆分为“:”并获取最后一段,这会产生: Looki_NEWS_1/08-14-14_yahoo
我不知道该怎么办。我尝试过正则表达式,但这似乎也不起作用。大家有这方面的经验吗?
最佳答案
意外的顺序是由'\r'
字符或回车符引起的。将其替换为 ''
或 ' '
,然后处理您的字符串。
str(attr_dict['title']).replace('\r', '')
考虑字符串:
st = "This is SO\rThat"
现在如果你打印字符串,
print st
That is SO
发生这种情况是因为当遇到 \r
或 回车
时,设备的位置会重置为文本行的开头。
关于python - 使用 Beautiful Soup 获取特定的 tr 元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27180283/