标签: beautifulsoup

使用BeautifulSoup,如何防范未被发现的元素?

我循环遍历表中的表行,但前1行或2行没有我要查找的元素(它们用于表列标题等).

因此,在说出第3个表行之后,表格单元格(td)中的元素具有我正在寻找的内容.

例如

td[0].a.img['src']
Run Code Online (Sandbox Code Playgroud)

但是调用它会失败,因为前几行没有这个.

How can I guard against these cases so my script doesn't fail?
Run Code Online (Sandbox Code Playgroud)

我得到的错误如下:

nonetype object is unsubscriptable
Run Code Online (Sandbox Code Playgroud)

python beautifulsoup

1
推荐指数
1
解决办法
2457
查看次数

BeautifulSoup用户的html5lib/lxml示例?

我试图从BeautifulSoup中解脱出来,我喜欢但似乎(积极地)不受支持.我正在尝试使用html5lib和lxml,但我似乎无法弄清楚如何使用"find"和"findall"运算符.

通过查看html5lib的文档,我想出了一个测试程序:

import cStringIO

f = cStringIO.StringIO()
f.write("""
  <html>
    <body>
      <table>
       <tr>
          <td>one</td>
          <td>1</td>
       </tr>
       <tr>
          <td>two</td>
          <td>2</td
       </tr>
      </table>
    </body>
  </html>
  """)
f.seek(0)

import html5lib
from html5lib import treebuilders
from lxml import etree  # why?

parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("lxml"))
etree_document = parser.parse(f)

root = etree_document.getroot()

root.find(".//tr")
Run Code Online (Sandbox Code Playgroud)

但是这会返回None.我注意到,如果我这样做,etree.tostring(root)我会收回所有数据,但我的所有标签都以html(例如<html:table>)开头.但root.find(".//html:tr")抛出一个KeyError.

有人能让我回到正轨吗?

python lxml beautifulsoup html5lib

1
推荐指数
2
解决办法
4671
查看次数

美丽的汤问题

我想在HTML文档中获取特定的行

这些行具有以下属性集:bgcolor和vallign

这是HTML表格的片段:

<table>
   <tbody>
      <tr bgcolor="#f01234" valign="top">
        <!--- td's follow ... -->
      </tr>
      <tr bgcolor="#c01234" valign="top">
        <!--- td's follow ... -->
      </tr>
   </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

我已经快速浏览了BS的文档.不清楚什么参数传递给findAll来匹配我想要的行.

有谁知道什么tp低音findAll()匹配我想要的行?

python beautifulsoup html-parsing

1
推荐指数
1
解决办法
474
查看次数

Python - BeautifulSoup - HTML解析

这是站点代码的片段

<td class='vcard' id='results100212571'>   
 <h2 class="custom_seeMore">
  <a class="fn openPreview" href="link.html">Hotel Name<span class="seeMore">See More...</span></a>
 </h2> 
 <div class='clearer'></div> 
 <div class='adr'>
  <span class='postal-code'>00000</span> 
  <span class='locality'>City</span> 
  <span class='street-address'>Address</span>
 </div>
 <p class="tel">Phone number</p>
Run Code Online (Sandbox Code Playgroud)

我试着解析它

for element in BeautifulSoup(page).findAll('td'):
    if element.find('a', {'class' : 'fn openPreview'}):
        print element.find('a', {'class' : 'fn openPreview'}).string
    if element.find('span', {'class' : 'postal-code'}):
        print element.find('span', {'class' : 'postal-code'}).string
    if element.find('span', {'class' : 'locality'}):
        print element.find('span', {'class' : 'locality'}).string
    if element.find('span', {'class' : 'street-address'}):
        print element.find('span', {'class' : 'street-address'}).string
    if element.find('p', {'class' : 'tel'}): …
Run Code Online (Sandbox Code Playgroud)

python beautifulsoup html-parsing

1
推荐指数
1
解决办法
3710
查看次数

如何在Python中使用BeautifulSoup删除HTML标记之间的空格?

我有以下问题:当html标签之间有空格时,我的代码不会给我输出的文本.

而不是输出:

year|salary|bonus
2005|100,000|50,000
2006|120,000|80,000
Run Code Online (Sandbox Code Playgroud)

我得到了这个:

 |salary|bonus
2005|100,000|50,000
2006|120,000|80,000
Run Code Online (Sandbox Code Playgroud)

未输出文本"年份".

这是我的代码:

from BeautifulSoup import BeautifulSoup
import re


html = '<html><body><table><tr><td> <p>year</p></td><td><p>salary</p></td><td>bonus</td></tr><tr><td>2005</td><td>100,000</td><td>50,000</td></tr><tr><td>2006</td><td>120,000</td><td>80,000</td></tr></table></html>'
soup = BeautifulSoup(html)
table = soup.find('table')
rows = table.findAll('tr')

store=[]

for tr in rows:
    cols = tr.findAll('td')
    row = []
    for td in cols:
        try:
            row.append(''.join(td.find(text=True)))
        except Exception:
            row.append('')
    store.append('|'.join(filter(None, row)))
print '\n'.join(store)
Run Code Online (Sandbox Code Playgroud)

问题来自于:

"<td> <p>year</p></td>"
Run Code Online (Sandbox Code Playgroud)

当我从网上提取一些HTML时,有没有办法摆脱那个空间?

html python tags beautifulsoup

1
推荐指数
1
解决办法
1917
查看次数

使用BeautifulSoup获取与扩展名匹配的文件名

我试图解析一个HTML页面,BeautifulSoup其中包含文本文件,以.txt扩展名结尾.我想解析HTML,并获取以...结尾的字符串.txt.

所有这些字符串都在一个<a href>标记内,这里有一些例子:

<a href = "foo.txt">

<a href = "bar.txt">

我怎么得到foo.txtbar.txt.

我这样做了:

>>> links = soup.findAll('a')

但是我找不到如何提取完整的字符串...有什么建议吗?

python beautifulsoup

1
推荐指数
1
解决办法
1584
查看次数

如何在阅读HTML文档中翻译/转换unicode转义<和>?

当我使用urllib2 opener在python中读取一些(但不是全部)HTML文件时,在某些文件中我得到的文本中填充了大量的反斜杠和unicode 003c字符串.我将此文本发送到BeautifulSoup并且无法使用findAll()找到我正在寻找的内容,而我现在认为这是由于所有这些unicode字符串.

这是怎么回事,我怎么摆脱它呢?

像soup.prettify()这样的方法没有效果.

这是一些示例代码(来自Facebook个人资料)

\\u003cdiv class=\\"pas status fcg\\">Loading...\\u003c\\/div>
\\u003c\\/div>\\u003cdiv class=\\"uiTypeaheadView fbChatBuddyListTypeaheadView dark hidden_elem\\" id=\\"u971289_14\\">\\u003c\\/div>
\\u003c\\/div>\\u003c\\/div>\\u003cdiv class=\\"fbNubFlyoutFooter\\">
\\u003cdiv class=\\"uiTypeahead uiClearableTypeahead fbChatTypeahead\\" id=\\"u971289_15\\">
\\u003cdiv class=\\"wrap\\">\\u003clabel class=\\"clear uiCloseButton\\" for=\\"u971291_21\\">
Run Code Online (Sandbox Code Playgroud)

在"查看源"窗口中,这个相同的HTML页面看起来很正常.

编辑:这是生成该文本的代码.奇怪的是,我没有从其他HTML页面获得这种输出.请注意,我已在此处用USERNAME和PASSWORD替换了用户名和密码.如果你替换这两个,你可以在自己的FB配置文件上尝试这个.

fbusername = "USERNAME@gmail.com"
fbpassword = "PASSWORD"
cookiefile = "facebook.cookies"

cj = cookielib.MozillaCookieJar(cookiefile)
if os.access(cookiefile, os.F_OK):
    cf.load()

opener = urllib2.build_opener(
    urllib2.HTTPRedirectHandler(),
    urllib2.HTTPHandler(debuglevel=0),
    urllib2.HTTPSHandler(debuglevel=0),
    urllib2.HTTPCookieProcessor(cj)
)

opener.addheaders = [('User-agent','Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1'),('Referer','http://www.facebook.com/')]

def facebooklogin():
    logindata = urllib.urlencode({
        'email' : fbusername,
        'pass' …
Run Code Online (Sandbox Code Playgroud)

html python beautifulsoup

1
推荐指数
1
解决办法
1335
查看次数

从代码中获取所有href

我正在制作一个网络爬虫.为了在页面中查找链接,我在selenium中使用xpath

driver = webdriver.Firefox()
driver.get(side)
Listlinker = driver.find_elements_by_xpath("//a")
Run Code Online (Sandbox Code Playgroud)

这很好.然而,测试爬虫,我发现并非所有链接都在a标签下.href有时也用在area或div标签中.

现在我被困住了

driver = webdriver.Firefox()
driver.get(side)
Listlinkera = driver.find_elements_by_xpath("//a")
Listlinkerdiv = driver.find_elements_by_xpath("//div")
Listlinkerarea = driver.find_elements_by_xpath("//area")
Run Code Online (Sandbox Code Playgroud)

这真的把爬行放在网络爬虫里.

我尝试过xpath "//@href",但这不起作用.我也尝试了几种方法来获得所有href url的有效方式,使用美丽的汤和lxml,但到目前为止,无济于事.对不起,我没有任何代码可以用美丽的汤和lxml显示我的努力,但由于这些被证明无用,我删除了它们,这不是最聪明的做法,我知道.我现在开始挽救这些不成功的尝试,为了我自己,如果我想再试一次,并想知道第一次出了什么问题

我能得到的任何帮助都将非常感激.

python selenium lxml beautifulsoup web-crawler

1
推荐指数
1
解决办法
4674
查看次数

Python Scraper - 如果目标是404'd,则套接字错误会破坏脚本

在构建Web剪贴板以编译数据并输出为XLS格式时遇到错误; 当再次测试我希望从中删除的域列表时,程序在收到套接字错误时会出错.希望找到一个'if'语句,它将解析一个破碎的网站并继续我的while循环.有任何想法吗?

workingList = xlrd.open_workbook(listSelection)
workingSheet = workingList.sheet_by_index(0)
destinationList = xlwt.Workbook()
destinationSheet = destinationList.add_sheet('Gathered')
startX = 1
startY = 0
while startX != 21:
    workingCell = workingSheet.cell(startX,startY).value
    print ''
    print ''
    print ''
    print workingCell
    #Setup
    preSite = 'http://www.'+workingCell
    theSite = urlopen(preSite).read()
    currentSite = BeautifulSoup(theSite)
    destinationSheet.write(startX,0,workingCell)
Run Code Online (Sandbox Code Playgroud)

这是错误:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    homeMenu()
  File "C:\Python27\farming.py", line 31, in homeMenu
    openList()
  File "C:\Python27\farming.py", line 79, in openList
    openList()
  File "C:\Python27\farming.py", line 83, in openList
    openList() …
Run Code Online (Sandbox Code Playgroud)

python sockets beautifulsoup

1
推荐指数
1
解决办法
652
查看次数

从美丽的汤创建一个HTML文件的问题

这是我使用BeautifulSoup的python代码.主要问题是属性.我正在寻找的是,th的每个元素应该是分开的,但由于某种原因它只在一个单独的标签内生成.

from BeautifulSoup import BeautifulSoup, Tag
soup=BeautifulSoup()
mem_attr=['Description','PhysicalID','Slot','Size','Width']
tag1 = Tag(soup, "html")
tag2 = Tag(soup, "table")
tag3 = Tag(soup, "tr")
tag4 = Tag(soup, "th")
tag5 = Tag(soup, "td")
soup.insert(0, tag1)
tag1.insert(0, tag2)
tag2.insert(0, tag3)
for i in range(0,len(mem_attr)):
        tag3.insert(0,tag4)
        tag4.insert(i,mem_attr[i])

print soup.prettify()
Run Code Online (Sandbox Code Playgroud)

这是它的输出:

<html>
 <table>
  <tr>
   <th>
    Description
    PhysicalID
    Slot
    Size
    Width
   </th>
  </tr>
 </table>
</html>
Run Code Online (Sandbox Code Playgroud)

我正在寻找的就是这个.

<html>
     <table>
      <tr>
       <th>
        Description
       </th>
       <th>
        PhysicalID
       </th>
       <th>
        Slot
       </th>
       <th>
        Size
       </th>
       <th>
        Width
       </th>
      </tr>
     </table>
    </html>
Run Code Online (Sandbox Code Playgroud)

谁能告诉我代码中缺少什么?

html python beautifulsoup

1
推荐指数
1
解决办法
3117
查看次数