我有一个带有标签的页面
<img alt="1ee7aca0cf5b0132dd7a005056a9545d" src="http://assets.amuniversal.com/1ee7aca0cf5b0132dd7a005056a9545d">
Run Code Online (Sandbox Code Playgroud)
我知道 XPath -
//*[@id="content"]/div[2]/p/a/img
Run Code Online (Sandbox Code Playgroud)
如何使用 BeautifulSoup 访问该标签并获取该标签的 src?
我正在抓取 sitemap.xml,我的目标是找到所有 url 和它们的增量计数。
下面是xml的结构
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.htcysnc.com/m/designer-sarees</loc>
<lastmod>2014-09-01</lastmod>
<changefreq>hourly</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>http://www.htcysnc.com/m/anarkali-suits</loc>
<lastmod>2014-09-01</lastmod>
<changefreq>hourly</changefreq>
<priority>0.9</priority>
</url>
Run Code Online (Sandbox Code Playgroud)
下面是我的代码
from BeautifulSoup import BeautifulSoup
import requests
import gzip
from StringIO import StringIO
def crawler():
count=0
url="http://www.htcysnc.com/sitemap/sitemap_product.xml.gz"
old_xml=requests.get(url)
new_xml=gzip.GzipFile(fileobj=StringIO(old_xml.content)).read()
#new_xml=old_xml.text
final_xml=BeautifulSoup(new_xml)
item_to_be_found=final_xml.findAll('loc')
for i in item_to_be_found:
count=count+1
print i
print count
crawler()
Run Code Online (Sandbox Code Playgroud)
我的输出是这样的
<loc>http://www.htcysnc.com/elegant-yellow-green-suit-seven-east-p63703</loc>
1
<loc>http://www.htcysnc.com/elegant-orange-pink-printed-suit-seven-east-p63705</loc>
2
Run Code Online (Sandbox Code Playgroud)
需要输出为没有 loc 和 /loc 的链接。已尝试替换命令,但会引发错误。
我对我在两个不同环境中编写的以下 HTML 抓取代码的行为完全感到困惑,需要帮助找到这种差异的根本原因。
import sys
import bs4
import md5
import logging
from urllib2 import urlopen
from platform import platform
# Log particulars of the environment
logging.warning("OS platform is %s" %platform())
logging.warning("Python version is %s" %sys.version)
logging.warning("BeautifulSoup is at %s and its version is %s" %(bs4.__file__, bs4.__version__))
# Open web-page and read HTML
url = 'http://www.ncbi.nlm.nih.gov/Traces/wgs/?val=JXIG&size=all'
response = urlopen(url)
html = response.read()
# Calculate MD5 to ensure that the same string was downloaded
print "MD5 sum for …Run Code Online (Sandbox Code Playgroud) 我有多个文本文件,用于存储来自网站的源页面。所以每个文本文件都是一个源页面。
我需要使用以下代码从存储在文本文件中的 div 类中提取文本:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("zing.internet.accelerator.plus.txt"))
txt = soup.find('div' , attrs = { 'class' : 'id-app-orig-desc' }).text
print txt
Run Code Online (Sandbox Code Playgroud)
我已经检查了我的汤对象的类型,以确保它在寻找 div 类时没有使用字符串查找方法。汤对象类型
print type(soup)
<class 'bs4.BeautifulSoup'>
Run Code Online (Sandbox Code Playgroud)
我已经参考了之前的一篇文章,并在beautifulsoup声明中写了公开声明。
错误:
Traceback (most recent call last):
File "html_desc_cleaning.py", line 13, in <module>
txt2 = soup.find('div' , attrs = { 'class' : 'id-app-orig-desc' }).text
AttributeError: 'NoneType' object has no attribute 'text'
Run Code Online (Sandbox Code Playgroud)
来自页面的来源:
您好,我正在使用 BeautifulSoup 4,我尝试替换汤文本中的“\n\t”字符。
这是我的代码:
soup = BS(html_doc, "html.parser")
for tableItem in soup.find_all("td"):
result = str(tableItem.string)
result = result.replace("\n\t\", "")
print(result)
Run Code Online (Sandbox Code Playgroud)
这是我的输出:
\n', '\t\t\t\t\t\t\t\t\t\tTEXT_I_WANT\t\t\t\t\t\t\t\t\t
Run Code Online (Sandbox Code Playgroud)
我用编码或beautifulsoup“NavigableString”尝试了几件事。我使用了错误的编码吗?或者有没有beautifulsoup的特殊方法。(例如stripped_strings)
ps:我可以替换 TEXT_I_WANT 但不能替换 "\n" 或 "\t"
我的 python 3.4.4 代码是:
import urllib.request
from bs4 import BeautifulSoup
from html.parser import HTMLParser
urls = 'file:///C:/Users/tarunuday/Documents/scrapdata/mech.html'
htmlfile = urllib.request.urlopen(urls)
soup = BeautifulSoup(htmlfile,html.parser)
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
Traceback (most recent call last):
File "C:\Python34\saved\scrapping\scrapping2.py", line 7, in <module>
soup = BeautifulSoup(htmlfile,html.parser)
NameError: name 'html' is not defined
Run Code Online (Sandbox Code Playgroud)
现在我明白 HTMLParser 是 py2.x 和 html.parser 是 py3.x 但我怎样才能让它工作?该BS4网站说If you get the ImportError “No module named html.parser”, your problem is that you’re running the Python 3 version of the code under Python 2. …
我有一个 ftp 链接,其中包含一些指向我有兴趣下载的文件的链接:
ftp://lidar.wustl.edu/Phelps_Rolla/
我可以使用以下内容列出所有网址:
import urllib2
import BeautifulSoup
request = urllib2.Request("ftp://lidar.wustl.edu/Phelps_Rolla/")
response = urllib2.urlopen(request)
soup = BeautifulSoup.BeautifulSoup(response)
Run Code Online (Sandbox Code Playgroud)
>>> soup
drwxrwxrwx 1 user group 0 Nov 7 2012 .
drwxrwxrwx 1 user group 0 Nov 7 2012 ..
drwxrwxrwx 1 user group 0 Nov 7 2012 ESRI_Grids
drwxrwxrwx 1 user group 0 Nov 7 2012 ESRI_Shapefiles
drwxrwxrwx 1 user group 0 Nov 7 2012 LAS_Files
-rw-rw-rw- 1 user group 545700 May 27 2011 LiDAR Accuracy Report_Rolla.pdf
drwxrwxrwx 1 user group …Run Code Online (Sandbox Code Playgroud) 我有一个方法,它使用 Beautifulsoup 从 HTML 文件中的标签返回文本列表。当我调用该方法时,我将从该方法返回的值保存到一个变量中。我认为是一个字符串变量。
我再次调用该方法并将返回值存储到不同的字符串变量中。我想连接这两个字符串,以便我可以在换行符上打印每个字符串。然后,我可以将其添加到我的电子邮件例程中,以便它将值打印到电子邮件消息中。
我收到错误:
Traceback (most recent call last):
File "E:/test_runners/selenium_regression_test_5_1_1/ClearCore - Regression Test/Email/email_selenium_report.py", line 43, in <module>
print rows_part1 + "/n" + rows_part2
TypeError: can only concatenate list (not "str") to list
Run Code Online (Sandbox Code Playgroud)
我的方法实现是:
def extract_data_from_report3(filename):
html_report_part = open(filename,'r')
soup = BeautifulSoup(html_report_part, "html.parser")
th = soup.find_all('th')
td = soup.find_all('td')
headers = [header.get_text(strip=True) for header in soup.find_all("th")]
rows = [dict(zip(headers, [td.get_text(strip=True) for td in row.find_all("td")]))
for row in soup.find_all("tr")[1:-1]]
print(rows)
return rows
Run Code Online (Sandbox Code Playgroud)
调用方法如下:
rows_part1 = report.extract_data_from_report3(r"E:\test_runners\selenium_regression_test_5_1_1\TestReport\SeleniumTestReport_part1.html")
print "part1 …Run Code Online (Sandbox Code Playgroud) 抓取网页后我有以下输出
text
Out[50]:
['\nAbsolute FreeBSD, 2nd Edition\n',
'\nAbsolute OpenBSD, 2nd Edition\n',
'\nAndroid Security Internals\n',
'\nApple Confidential 2.0\n',
'\nArduino Playground\n',
'\nArduino Project Handbook\n',
'\nArduino Workshop\n',
'\nArt of Assembly Language, 2nd Edition\n',
'\nArt of Debugging\n',
'\nArt of Interactive Design\n',]
Run Code Online (Sandbox Code Playgroud)
我需要在迭代它时从上面的列表中去除 \n 。以下是我的代码
text = []
for name in web_text:
a = name.get_text()
text.append(a)
Run Code Online (Sandbox Code Playgroud) 我现在正在读一本关于 Python 的书。有一个家庭作业的小项目:“编写一个程序,访问 Flickr 或 Imgur 等照片共享网站,搜索一类照片,然后下载所有生成的图像。” 建议只使用 webbrowser、requests 和 bs4 库。
我不能为 Flickr 做这件事。我发现解析器不能进入元素内部(div class="interaction-view")。在 Chrome 中使用“Inspect element”我可以看到里面有一些“div”元素和“a”元素。但是,当我使用 bs4 库时,它看不到它。
我的代码是这样的:
#!/usr/bin/env python3
# To download photos from Flickr
import requests, bs4
search_name = "spam"
website_name = requests.get('https://www.flickr.com/search/?text='
+ search_name)
website_name.raise_for_status()
parse_obj = bs4.BeautifulSoup(website_name.text, "html.parser")
elements = parse_obj.select('body #content main .main.search-photos-results \
.view.photo-list-view.requiredToShowOnServer \
.view.photo-list-photo-view.requiredToShowOnServer.awake \
.interaction-view')
print(elements)
Run Code Online (Sandbox Code Playgroud)
它只打印:
[<div class="interaction-view"></div>, <div class="interaction-view"></div>...]
Run Code Online (Sandbox Code Playgroud)
没有任何嵌套元素,我不明白为什么...谢谢!
beautifulsoup ×10
python ×9
python-2.7 ×2
web-scraping ×2
download ×1
flickr ×1
ftp ×1
html ×1
html-parsing ×1
parsing ×1
python-3.x ×1
replace ×1
web-crawler ×1
xml ×1