python - 使用 BS4 python 进行抓取

标签 python web-scraping beautifulsoup screen-scraping

我正在使用以下代码从网站上抓取数据。

from bs4 import BeautifulSoup
import urllib2
import re
for i in xrange(1,461,10):
  try:
    page = urllib2.urlopen("http://cms.onlinedemos.in/directory.php?click=n&startline={}#lst".format(i))
  except urllib2.HTTPError:
    continue
  else:
    pass
  finally:
    soup = BeautifulSoup(page)
    td1=soup.findAll('td', {'class':'comtext'})
    td2 = soup.findAll('td',{'class':'comuser'})
    td3 = soup.findAll('td',{'class':'com'})
    for td1s, td2s, td3s in zip(td1,td2,td3):
      data = [re.sub('\s+', '', text).strip().encode('utf8') for text in td1s.find_all(text=True) + td2s.find_all(text=True) + td3s.find_all(text=True)  if text.strip()]
      print ','.join(data)

我的输出是

A.T.E.EnterprisesPvt.Ltd.,,AnujBhagwati
A.T.E.Pvt.Ltd.,,AtulBhagwati
AalidhraTextileEngineersLtd.,,HansrajGondalia,Mumbai
AarBeeAssociates,Mr.Gopalsamy,022-22872245
ABCarterIndiaPvt.Ltd.,,B.B.Shetty,fort@ateindia.com
ABCCorporation,MittalPatel,Mumbai
ABCIndustrialFasteners,S.R.Sheth,022-22872245

但是应该是这样的

    A.T.E. Enterprises Pvt. Ltd.,   Anuj Bhagwati   Mumbai  022-22872245    fort@ateindia.com    

    A.T.E. Pvt. Ltd.,   Atul Bhagwati   Mumbai  022-22872245    fort@ateindia.com    

    Aalidhra Textile Engineers Ltd.,    Hansraj Gondalia    Surat   0261-2279520/30/40  aalidhra@aalidhra.com    

    Aar Bee Associates  Mr. Gopalsamy   Coimbatore  0422-2236250 / 2238560  aarbeeassociates@rediffmail.com  

因此,您可以看到第一行值 Mumbai 022-22872245 fort@ateindia.com 开始落在第三、第四和第五行。一切都会继续下去。我知道我哪里错了。

最佳答案

看一下这个页面的 HTML,每行有 3 列 com 类。将包含 10 个项目的列表与另一个包含 10 个项目的列表和第三个包含 30 个项目的列表进行压缩将得到您所获得的输出类型。

>>> len(td3)
30
>>> td3[0:3]
[<td class="com" width="100"></td>, <td class="com" width="160"></td>, <td class="com" width="185"></td>]
>>> td3[3:6]
[<td class="com" width="100">Mumbai</td>, <td class="com" width="160">022-22872245</td>, <td class="com" width="185">fort@ateindia.com</td>]

关于python - 使用 BS4 python 进行抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20103542/

相关文章:

Python 语法错误 : invalid syntax for "elif len(org) >= 1:"

node.js - 如何从 Google Cloud Function(Cheerio、Node.js)发出多个 http 请求

python - 当我使用 concurrent.futures 时,无法弄清楚如何将结果写回同一个工作表

java - jsoup:解析特定标签之后的特定标签的数据

Python:使用 BeautifulSoup4 的简单网络爬虫

python - 使用 Python 从 HTML 中提取字符串不适用于正则表达式或 BeautifulSoup

python - 如何在 python 中使用 beautifulsoup 从 "span"标签和 "data-reactid"抓取数据?

python - 在 for-else 循环中是否存在与 "else"相反的行为?

python - 为什么用 OpenCV 保存图像会产生黑色图像?

python - 皮卡没有属性日志